There should only be one top-level function.
var datex = require('data-expression');
Evaluation rules:
// one argument produces an evaluator, even if there aren't any variables
assert.equal(typeof datex('1 + 2'), 'function');
// two arguments evaluates the expression
assert.equal(datex('a + b', {a: 1, b: 2}), 3);
// or you can just call the evaluator without any arguments
assert.equal(datex('1 + 2')(), 3);
Setting context variables:
// expressions can have variables set programmatically
var expr = datex('a + b')
.set('a', 1)
.set('b', 2);
// calling it without any arguments evaluates it
assert.equal(expr(), 3);
// or you can call it with some data and those variables will be merged
assert.equal(expr({a: 2}), 4);
// you can pass an object to set()
expr.set({a: 1, b: 100});
assert.equal(expr(), 101);
Setters should be handled transparently:
var expr = datex('foo = foo.map(x => x + 1)');
var data = {foo: [1, 2, 3]};
assert.deepEqual(expr(data), [2, 3, 4]);
assert.deepEqual(data, {foo: [2, 3, 4]});
Maps:
var expr = datex.map('{foo: Foo.toLowerCase()}');
assert.deepEqual(expr({Foo: 'BLAH'}), {foo: 'blah'});
Question: should we just wrap the statement in parens (so it isn't parsed as a BlockStatement
), or should we check to see if the parsed node is a BlockStatement
and return a parenthesis-wrapped statement automatically? Doing this would have performance implications.
Maybe programmatic maps?
var expr = datex.map({
foo: 'Foo.toLowerCase()',
date: 'moment(Date).format("YYYY-MM-DD")'
})
.require('moment');
// note: "Date" above is a variable, not the global Date object
var data = {Foo: 'BLAH', Date: '6/12/81'};
assert.deepEqual(expr(data), {foo: 'blah', date: '1981-06-12'});
// it doesn't modify the data!
assert.deepEqual(data, {Foo: 'BLAH', Date: '6/12/81'});
// the keys are evaluated in order, so you can use previously evaluated keys
// in late key expressions
expr.key('bar', 'foo + " bar"');
assert.deepEqual(expr(data), {foo: 'blah', date: '1981-06-12', bar: 'blah bar'});
This is the type of thing that could be used for interactive data transformation, and would be easier to work with than constructing the assignment expressions or the map()
expression above.