Skip to content

Commit

Permalink
support 'in' operator
Browse files Browse the repository at this point in the history
  • Loading branch information
William committed Oct 29, 2018
1 parent a309843 commit 5705767
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 2 deletions.
9 changes: 8 additions & 1 deletion __tests__/evaluate.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import evaluate, { registerFunction } from '../src';
import { parseExpression, parse } from '@babel/parser';
import { objectExpression } from '@babel/types';

const context = {
str: 'string',
Expand Down Expand Up @@ -115,8 +116,14 @@ describe('evaluate expression', () => {
expect(evaluate('obj[obj.b.c]', context)).toEqual('ccc');
});

it('str ? obj.a : 123', () => {
it('? : ', () => {
expect(evaluate('str ? obj.a : 123', context)).toEqual(1);
expect(evaluate('!str ? obj.a : 123', context)).toEqual(123);
});

it('in operator', () => {
expect(evaluate('1 in arr', context)).toBeTruthy();
expect(evaluate('6 in arr', context)).toBeFalsy();
expect(evaluate('6 in undefined', context)).toBeFalsy();
})
});
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "ts-expression-evaluator",
"version": "1.3.9",
"version": "1.3.10",
"description": "Context-based expression parse and evaluator.",
"main": "build/main/index.js",
"typings": "build/main/index.d.ts",
Expand Down
5 changes: 5 additions & 0 deletions src/lib/Handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,11 @@ export const Handlers: Handlers = {
return evaluate(ast.left, context) < evaluate(ast.right, context);
case '<=':
return evaluate(ast.left, context) <= evaluate(ast.right, context);
case 'in': {
const container = evaluate(ast.right, context);
if (!container) return false;
return evaluate(ast.left, context) in container;
}
}
}
throw new Error();
Expand Down

0 comments on commit 5705767

Please sign in to comment.