Skip to content

Commit

Permalink
feat(json-expression): 🎸 add codege support for "ne" expression
Browse files Browse the repository at this point in the history
  • Loading branch information
streamich committed Nov 25, 2021
1 parent 02bd3f8 commit 4e04425
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
25 changes: 24 additions & 1 deletion src/json-expression/__tests__/codegen.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,27 @@ describe('eq', () => {
check(['eq', 'bar', ['eq', 1, 1]], false);
check(['eq', true, ['eq', 1, 1]], true);
});
});

test('together with get', () => {
check(['eq', 3, ['=', '/foo']], true, {foo: 3});
});
});

describe('ne', () => {
test('on two literals', () => {
check(['!=', 1, 2], true);
check(['!=', {foo: 'bar'}, {foo: 'bar'}], false);
check(['!=', {foo: 'bar'}, {foo: 'baz'}], true);
check(['!=', [[]], [[]]], false);
});

test('literal and expression', () => {
check(['ne', 3, ['=', '/foo']], true);
check(['ne', 'bar', ['eq', 1, 1]], true);
check(['!=', true, ['eq', 1, 1]], false);
});

test('together with get', () => {
check(['ne', 3, ['=', '/foo']], false, {foo: 3});
});
});
10 changes: 9 additions & 1 deletion src/json-expression/codegen.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type {Expr, ExprEquals, ExprGet, JsonExpressionCodegenContext, JsonExpressionExecutionContext} from './types';
import type {Expr, ExprEquals, ExprGet, ExprNotEquals, JsonExpressionCodegenContext, JsonExpressionExecutionContext} from './types';
import {Codegen} from '../util/codegen/Codegen';
import {deepEqual} from '../json-equal/deepEqual';
import {toPath, get as get_} from '../json-pointer';
Expand Down Expand Up @@ -106,6 +106,12 @@ export class JsonExpressionCodegen {
return new Expression(`deepEqual(${this.onExpression(a as Expr)}, ${this.onExpression(b as Expr)})`);
}

protected onNotEquals([, a, b]: ExprNotEquals): ExpressionResult {
const res = this.onEquals(['eq', a, b]);
if (res instanceof Literal) return new Literal(!res.val);
return new Expression(`!(${res})`);
}

protected onExpression(expr: Expr | unknown): ExpressionResult {
if (!isExpression(expr)) {
if (expr instanceof Array) {
Expand All @@ -120,6 +126,8 @@ export class JsonExpressionCodegen {
case 'get': return this.onGet(expr as ExprGet);
case '==':
case 'eq': return this.onEquals(expr as ExprEquals);
case '!=':
case 'ne': return this.onNotEquals(expr as ExprNotEquals);
}
return new Literal(false);;
}
Expand Down

0 comments on commit 4e04425

Please sign in to comment.