0.3.1 • Published 8 years ago
jseval v0.3.1
jseval
Compile time function evaluator for javascript and AST
Examples
Basic Usage
Simple usage for jseval
const evalFunctions = {
$my_fn: function( id ) { return 'my_id_'+id; },
$inline: function( fn ) { return fn(); },
};
const src = `
var x = 10;
var y = $my_fn(30);
var z = $inline(function() {
var ary = [];
for ( var i = 0; i < 100; ++i )
ary.push( i );
return ary;
});
`;
jseval( src, evalFunctions )
.then(function( output ) {
/*
Expected Output:
var x = 10;
var y = 'my_id_30';
var z = [0,1,2,3,4,...,99];
*/
console.log( output );
});
Async
Async evaluation
const evalFunctions = {
$async: function() {
return Promise.delay(1000)
.then(function() { return 'async value'; }
;
},
};
const src = `
var x = $async();
`;
jseval( src, evalFunctions )
.then(function( output ) {
/*
Expected Output after 1000ms delay:
var x = 'async value';
*/
console.log( output );
});
Eval Functions
An eval function is a function to be compiled by jsval. It allows the return of promises to defer its evaluation.
const evalFunctions = {
$include: function( filename ) {
return /* some promise that reads the file */;
}
}
Methods
jseval( src, evalFunctions, options )
Source to source evaluation
- src {String}: The string to be evaluated
- evalFunctions {object}: A map of functions to be runned when encountered
options {object}:
- options.source {string}: If passed, the string will be used as a source filename for sourcemap generation
- options.Promise {object}: The Promise library to be used (must have at least Promise.all, Promise.resolve)
Returns {Promise} A promise with the output string if no source-map is requested. Otherwise an object with code and map properties.
jseval.evalAST( ast, evalFunctions, options )
AST to AST evaluation
- ast {object}: The AST to be evaluated