Skip to content

Commit

Permalink
feat: tenery operator
Browse files Browse the repository at this point in the history
  • Loading branch information
arlac77 committed Jan 5, 2017
1 parent d0c758e commit 5756aa2
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/grammar.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,17 @@ class BinOP extends AST {
}
}

class TeneryOP extends AST {
constructor(exp, a, b) {
super();
Object.defineProperty(this, 'value', {
get: () => {
return exp.value ? a.value : b.value;
}
});
}
}

class FCall extends AST {
constructor(f, context, args) {
super();
Expand Down Expand Up @@ -170,6 +181,15 @@ export const grammar = create({
}
},
infix: {
'?': {
precedence: 20,
led(grammar, left) {
const e1 = grammar.expression(0);
grammar.advance(':');
const e2 = grammar.expression(0);
return new TeneryOP(left, e1, e2);
}
},
'.': {
precedence: 1,
combine: (left, right) => new ObjectAccess(left, right)
Expand All @@ -178,6 +198,7 @@ export const grammar = create({
precedence: 1,
combine: (left, right) => new ArrayAccess(left, right)
},
':': {},
']': {},
',': {},
')': {},
Expand Down
13 changes: 13 additions & 0 deletions tests/simple_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,19 @@ describe('expander', () => {
});
});

describe('tenery expression', () => {
it('true 1st.', () => expand("${2 > 1 ? 22 : 11}").then(r => assert.equal(r, 22)));
it('false 2nd.', () => expand("${2 < 1 ? 22 : 11}").then(r => assert.equal(r, 11)));

describe('combined', () => {
it('false 2nd.', () => expand("${2 < 1 ? 22+1 : 11+1}").then(r => assert.equal(r, 12)));
it('true 2nd.', () => expand("${2*0 < 1 ? 22+1 : 11+1}").then(r => assert.equal(r, 23)));
it('true 2nd. with function call', () => expand("${'a'=='b' ? 22+1 : substring('abc',1,2)}").then(r =>
assert.equal(r,
'b')));
});
});

describe('functions', () => {
it('unknown function', () => expand("${thisFunctionIsUnknown()}")
.then(e => assert.equal(e, {}))
Expand Down

0 comments on commit 5756aa2

Please sign in to comment.