static-eval2
evaluate statically-analyzable expressions
Last updated 2 years ago by goto-bus-stop .
MIT · Repository · Bugs · Original npm · Tarball · package.json
$ cnpm install static-eval2 
SYNC missed versions from official npm registry.

static-eval

evaluate statically-analyzable expressions

testling badge

build status

example

var evaluate = require('static-eval');
var parse = require('esprima').parse;

var src = process.argv[2];
var ast = parse(src).body[0].expression;

console.log(evaluate(ast));

If you stick to simple expressions, the result is statically analyzable:

$ node '7*8+9'
65
$ node eval.js '[1,2,3+4*5-(5*11)]'
[ 1, 2, -32 ]

but if you use statements, undeclared identifiers, or syntax, the result is no longer statically analyzable and evaluate() returns undefined:

$ node eval.js '1+2+3*n'
undefined
$ node eval.js 'x=5; x*2'
undefined
$ node eval.js '5-4*3'
-7

You can also declare variables and functions to use in the static evaluation:

var evaluate = require('static-eval');
var parse = require('esprima').parse;

var src = '[1,2,3+4*10+n,foo(3+5),obj[""+"x"].y]';
var ast = parse(src).body[0].expression;

console.log(evaluate(ast, {
    n: 6,
    foo: function (x) { return x * 100 },
    obj: { x: { y: 555 } }
}));

methods

var evaluate = require('static-eval');

evaluate(ast, vars={})

Evaluate the esprima-parsed abstract syntax tree object ast with an optional collection of variables vars to use in the static expression resolution.

If the expression contained in ast can't be statically resolved, evaluate() returns undefined.

install

With npm do:

npm install static-eval

license

MIT

Current Tags

  • 2.0.1                                ...           latest (2 years ago)

1 Versions

  • 2.0.1                                ...           2 years ago
Maintainers (1)
Downloads
Today 0
This Week 6
This Month 11
Last Day 1
Last Week 5
Last Month 35
Dependencies (1)
Dev Dependencies (2)
Dependents (1)

Copyright 2014 - 2017 © taobao.org |