Skip to content
This repository was archived by the owner on Feb 26, 2024. It is now read-only.

Adding unary operator + to transform string into numbers #10

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions src/ast.js
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,7 @@ export class Binary extends Expression {

// Null check for the operations.
if (left == null || right == null) {

switch (this.operation) {
case '+':
if (left != null) return left;
Expand Down Expand Up @@ -366,6 +367,24 @@ export class PrefixNot extends Expression {
}
}


export class PrefixPlus extends Expression {
constructor(operation:string, expression:Expression){
super();

this.operation = operation;
this.expression = expression;
}

eval(scope, filters=defaultFilterMap){
return +this.expression.eval(scope);
}

accept(visitor){
visitor.visitPrefix(this);
}
}

export class LiteralPrimitive extends Expression {
constructor(value){
super();
Expand Down
4 changes: 2 additions & 2 deletions src/parser.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {Lexer,Token} from './lexer';
import {Expression,ArrayOfExpression,Chain,Filter,Assign,
Conditional, AccessScope, AccessMember, AccessKeyed,
CallScope, CallFunction, CallMember, PrefixNot,
CallScope, CallFunction, CallMember, PrefixNot, PrefixPlus,
Binary, LiteralPrimitive, LiteralArray, LiteralObject, LiteralString} from './ast';

var EOF = new Token(-1, null);
Expand Down Expand Up @@ -205,7 +205,7 @@ export class ParserImplementation {

parsePrefix():Expression {
if (this.optional('+')) {
return this.parsePrefix(); // TODO(kasperl): This is different than the original parser.
return new PrefixPlus('+', this.parsePrefix());
} else if (this.optional('-')) {
return new Binary('-', new LiteralPrimitive(0), this.parsePrefix());
} else if (this.optional('!')) {
Expand Down
5 changes: 5 additions & 0 deletions test/parser.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,12 @@ describe('parser', () => {

it('should parse unary - expressions', () => {
expect(evaluate("-1")).toEqual(-1);
});

it('should parse unary + expressions', () => {
expect(evaluate("+1")).toEqual(1);
expect(evaluate("+'1'")).toEqual(1);
expect(evaluate("+'not a number'")).toEqual(NaN);
});

it('should parse unary ! expressions', () => {
Expand Down