This package has been deprecated

Author message:

This package is no longer maintained.

string-expression

0.0.6 • Public • Published

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.

 
import Interpreter from 'string-expression;
 
var i = new Interpreter();
 
var context = {
  a: 5,
  b: 5,  
  resolve(key) {    
    return this[key];
  }
};
 
i.evaluate('a-b', {a:5,b:5}); //returns 0
i.evaluate('a+b', {a:5,b:5}); //returns 10
i.evaluateWithContext('a/b', context); //returns 1
 

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

Readme

Keywords

Package Sidebar

Install

npm i string-expression

Weekly Downloads

0

Version

0.0.6

License

Apache 2

Last publish

Collaborators

  • metasansana