Implement unary expressions
This commit is contained in:
parent
6237c8caea
commit
d82737fb81
|
@ -5,6 +5,23 @@ import * as peggy from 'peggy';
|
|||
|
||||
const grammar = `
|
||||
{{
|
||||
function evaluateUnaryExpression( operator, operand ) {
|
||||
switch ( operator ) {
|
||||
case '!':
|
||||
return !operand;
|
||||
break;
|
||||
case '-':
|
||||
return -operand;
|
||||
break;
|
||||
case '+':
|
||||
return +operand;
|
||||
break;
|
||||
default:
|
||||
return undefined;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
function evaluateBinaryExpression( head, tail ) {
|
||||
return tail.reduce( ( leftOperand, tailElement ) => {
|
||||
const operator = tailElement[ 1 ];
|
||||
|
@ -262,8 +279,19 @@ PrimaryExpression
|
|||
return expression;
|
||||
}
|
||||
|
||||
RelationalExpression
|
||||
UnaryExpression
|
||||
= PrimaryExpression
|
||||
/ operator:UnaryOperator WhiteSpace* operand:UnaryExpression {
|
||||
return evaluateUnaryExpression( operator, operand );
|
||||
}
|
||||
|
||||
UnaryOperator
|
||||
= "!"
|
||||
/ "-"
|
||||
/ "+"
|
||||
|
||||
RelationalExpression
|
||||
= UnaryExpression
|
||||
|
||||
EqualityExpression
|
||||
= head:RelationalExpression tail:( WhiteSpace* EqualityOperator WhiteSpace* RelationalExpression)* {
|
||||
|
|
|
@ -196,6 +196,18 @@ describe( 'parser', () => {
|
|||
expect( result ).toEqual( true );
|
||||
} );
|
||||
|
||||
it( 'should parse a negative number', () => {
|
||||
const result = parser.parse( '-1' );
|
||||
|
||||
expect( result ).toEqual( -1 );
|
||||
} );
|
||||
|
||||
it( 'should parse a positive number', () => {
|
||||
const result = parser.parse( '+1' );
|
||||
|
||||
expect( result ).toEqual( 1 );
|
||||
} );
|
||||
|
||||
it( 'should throw an error if the expression is invalid', () => {
|
||||
expect( () => parser.parse( '= 1' ) ).toThrow();
|
||||
} );
|
||||
|
|
Loading…
Reference in New Issue