string-expression
Library for evaluating simple string expressions
Motivation
We needed to execute some logic based on some simple JavaScript expressions without using eval etc.
Usage
This module is meant to be used as part of a browserify build. It's written using ES6/ES2015 syntax but is transpiled with babel so that should not be an issue.
Context
is an interface you can implement to customise how variables
are resolved. It has a single method resolve(key)
.
Supported Syntax
Unary Operations
example:
!a
or 2
syntax:
OPERAND
or prefix operator to OPERAND
where:
OPERAND can be a variable name or a primitive (string or number), it can be prefixed with !
Binary Operations
example:
a+b
syntax:
LEFT_OPERAND OPERATOR RIGHT_OPERAND
where:
LEFT_OPERAND and RIGHT_OPERAND can be both be a variable name or a primitive (string or number)
OPERATOR is any of ==,%,<,<=,>,>=,/,*,+,-
, note ==
and !=
uses strict checks.
Ternary Operations
example:
(a) ? b : a
syntax:
EXPRESSION ? OPERAND : OPERAND
where: You get the point
Notes
Whitespace is important, keep one space between operators an operands except for unary operations. Where a variable is not resolved an empty string is returned.
License
Apache 2