Skip to content

Commit

Permalink
feat(interpreter): allow passing external variables
Browse files Browse the repository at this point in the history
fixes #174
  • Loading branch information
kantord committed Dec 24, 2018
1 parent 5d74903 commit 37163b8
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 3 deletions.
14 changes: 14 additions & 0 deletions src/__tests__/interpreter.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -460,6 +460,20 @@ describe('interpreter', () => {
}
)

it(`allow passing single variable`, () => {
expect(execute('$foo')(null, { foo: 3 })).toEqual(3)
})

it(`allow passing multiple variables`, () => {
expect(execute('$foo + $bar')(null, { foo: 4, bar: -2 })).toEqual(2)
})

it(`doesn't allow passing functions`, () => {
expect((): mixed =>
execute('foo 4')(null, { foo: (x: ?mixed): number => 3 })
).toThrow()
})

it('throws syntax error on invalid source code', () => {
expect(() => {
execute('¡')
Expand Down
10 changes: 8 additions & 2 deletions src/interpreter.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,11 @@ import compiler from './compiler'
import type { OutputType, SourceCodeType } from './types'
import builtIns from './builtins.js'

export default (input: SourceCodeType): OutputType =>
eval(compiler(input))(builtIns) // eslint-disable-line no-eval
export default (sourceCode: SourceCodeType): OutputType => {
const compiledFunction = eval(compiler(sourceCode)) // eslint-disable-line no-eval
return (input: mixed, variables?: {[string]: mixed}): mixed =>
compiledFunction({
...builtIns,
...JSON.parse(JSON.stringify(variables || {}))
})(input)
}
2 changes: 1 addition & 1 deletion src/types.js
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ export type ProjectableNodeType =

export type AssignmentType = [PrimitiveNodeType, NodeType];
export type AssignmentsType = Array<AssignmentType>;
export type OutputType = mixed => mixed;
export type OutputType = (input: mixed, variables?: {[string]: mixed}) => mixed;
export type SourceCodeType = string;
export type GeneratedCodeType = string;
export type ParserType = SourceCodeType => ParserReturnValueType;

0 comments on commit 37163b8

Please sign in to comment.