diff --git a/src/ast.js b/src/ast.js index 6e570af1..57842cef 100644 --- a/src/ast.js +++ b/src/ast.js @@ -459,15 +459,15 @@ export class Binary extends Expression { } // Null check for the operations. - if (left === null || right === null) { + if (left === null || right === null || left === undefined || right === undefined) { switch (this.operation) { // eslint-disable-line case '+': - if (left !== null) return left; - if (right !== null) return right; + if (left !== null && left !== undefined) return left; + if (right !== null && right !== undefined) return right; return 0; case '-': - if (left !== null) return left; - if (right !== null) return 0 - right; + if (left !== null && left !== undefined) return left; + if (right !== null && right !== undefined) return 0 - right; return 0; } diff --git a/test/ast/binary.spec.js b/test/ast/binary.spec.js new file mode 100644 index 00000000..311cc334 --- /dev/null +++ b/test/ast/binary.spec.js @@ -0,0 +1,48 @@ +import {Binary, LiteralString, LiteralPrimitive} from '../../src/ast'; +import {createScopeForTest} from '../../src/scope'; + +describe('Binary', () => { + it('concats strings', () => { + let expression = new Binary('+', new LiteralString('a'), new LiteralString('b')); + let scope = createScopeForTest({}); + expect(expression.evaluate(scope, null)).toBe('ab'); + + expression = new Binary('+', new LiteralString('a'), new LiteralPrimitive(null)); + scope = createScopeForTest({}); + expect(expression.evaluate(scope, null)).toBe('a'); + + expression = new Binary('+', new LiteralPrimitive(null), new LiteralString('b')); + scope = createScopeForTest({}); + expect(expression.evaluate(scope, null)).toBe('b'); + + expression = new Binary('+', new LiteralString('a'), new LiteralPrimitive(undefined)); + scope = createScopeForTest({}); + expect(expression.evaluate(scope, null)).toBe('a'); + + expression = new Binary('+', new LiteralPrimitive(undefined), new LiteralString('b')); + scope = createScopeForTest({}); + expect(expression.evaluate(scope, null)).toBe('b'); + }); + + it('adds numbers', () => { + let expression = new Binary('+', new LiteralPrimitive(1), new LiteralPrimitive(2)); + let scope = createScopeForTest({}); + expect(expression.evaluate(scope, null)).toBe(3); + + expression = new Binary('+', new LiteralPrimitive(1), new LiteralPrimitive(null)); + scope = createScopeForTest({}); + expect(expression.evaluate(scope, null)).toBe(1); + + expression = new Binary('+', new LiteralPrimitive(null), new LiteralPrimitive(2)); + scope = createScopeForTest({}); + expect(expression.evaluate(scope, null)).toBe(2); + + expression = new Binary('+', new LiteralPrimitive(1), new LiteralPrimitive(undefined)); + scope = createScopeForTest({}); + expect(expression.evaluate(scope, null)).toBe(1); + + expression = new Binary('+', new LiteralPrimitive(undefined), new LiteralPrimitive(2)); + scope = createScopeForTest({}); + expect(expression.evaluate(scope, null)).toBe(2); + }); +});