Product
Introducing SSO
Streamline your login process and enhance security by enabling Single Sign-On (SSO) on the Socket platform, now available for all customers on the Enterprise plan, supporting 20+ identity providers.
expression-runner
Advanced tools
Readme
Simple JavaScript expression compiler: given a JavaScript expression as a string, generates a function that evaluates the expression.
Install: npm install expression-runner
The following JavaScript syntax is allowed within compiled expressions:
[1, 2]
, { a: 1 }
, { a, b }
)(a) => a + 1
, but only using a single expression)??
and ?.
operatorsa ? b : c
)a = 1
, b += 2
), but not ++
and --
Function calls may include calls to default functions (see list below), as well as 'safe' methods on strings, numbers, arrays, dates, and the RegExp test
method; these do not modify anything other than the original value.
Multiple expressions are allowed, separated by semicolons OR newlines.
Only the result of the last expression is returned by the compiled function, however each intermediate result is available as $_
.
This allows for running a block of expressions, although branching and looping is not available (since statements are not compiled).
[3, 2, 1]
sort($_)
$_.map(i => "(" + i + ")")
$_.join(",")
The code above results in the string "(1),(2),(3)"
The easiest way to use this library is with the compile()
method:
let myVars = { a: 1 };
const f1 = compile("a + 1");
let result = f1(myVars);
console.log(result) // => 2
Expressions can also be assignments, but those cannot appear in the middle of another expression (e.g. not a = (b = 2)
but b = 2
itself is allowed).
To allow assignments, pass true
as the second argument to the compile
function.
let myVars = {};
const f2 = compile("a = 42", true);
f2(myVars);
console.log(myVars.a) // => 42
The final argument to the compile
function can be used to pass additional functions that will be available within the compiled expression.
let check = 0;
const setCheck = (i) => { check = i };
const f3 = compile("set(42)", false, { set: setCheck });
f3();
console.log(setCheck) // => 42
For manual compilation, especially if you do not want to make the default functions available or if you want to run the same expression multiple times within the same scope (variables), use the following exported classes:
Compiler
new Compiler(expr)
ic = compiler.compile()
; optionally, pass in true
to allow assignments at the top level.Runtime
scopeFactory
method to create a Runtime
constructor that encapsulates the intermediate code: R = Runtime.scopeFactory(ic)
new R(vars, fns)
. This represents the 'scope' that the expression code will run inRuntime.functions
Runtime
object's run()
method evaluates the expression, and returns its result: result = r.run()
Other than 'safe' methods on strings, numbers, arrays, dates, and regular expressions (created using the regexp
function, since regular expression literals are not allowed), the following 'global' functions are available within expressions.
abs
, floor
, ceil
, round
, min
, max
, pow
, sqrt
, random
typeof(value)
— result of typeof value
in JavaScriptstr(value)
— convert to stringchr(value)
— get string from character code (unicode)parseFloat(value)
— same as JavaScript parseFloat
parseInt(value)
— same as JavaScript parseInt
isDefined(value)
— returns true if value is not undefined or nullisArray(value)
— same as JavaScript Array.isArray(...)
isObject(value)
— returns true if value is a plain objectkeys(object)
— same as JavaScript Object.keys(...)
merge(...objects)
— returns a new object with all properties from given objectsconcat(...arrays)
— returns a new array with all elements from given arrayssort(array, [compareFn])
— returns a copy of the array that is sorted; the comparison function is optional, a default is provided that works well for both strings and numberssortBy(arrayOfObjects, propertyName)
- returns a copy of the array that is sorted by the property with given namereverse(array)
— returns a copy of the array in reverse orderrange(start, length)
— returns an array of numbers starting with start
, of given lengthtoJSON(value)
— same as JavaScript JSON.stringify(...)
parseJSON(string)
— same as JavaScript JSON.parse(...)
regexp(patternString, [flags])
— same as JavaScript new RegExp(...)
match(string, patternString, [flags])
— same as JavaScript string.match(...)
date(...values)
— same as JavaScript new Date(...)
dateUTC(y, m, ...d)
— same as JavaScript new Date(Date.UTC(y, m, ...))
now()
— same as JavaScript Date.now()
(i.e. returns a number)encodeURI(string)
— same as JavaScript encodeURI(...)
encodeURIComponent(string)
— same as JavaScript encodeURIComponent(...)
FAQs
Compile and run JavaScript expressions safely
The npm package expression-runner receives a total of 7 weekly downloads. As such, expression-runner popularity was classified as not popular.
We found that expression-runner demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Streamline your login process and enhance security by enabling Single Sign-On (SSO) on the Socket platform, now available for all customers on the Enterprise plan, supporting 20+ identity providers.
Security News
Tea.xyz, a crypto project aimed at rewarding open source contributions, is once again facing backlash due to an influx of spam packages flooding public package registries.
Security News
As cyber threats become more autonomous, AI-powered defenses are crucial for businesses to stay ahead of attackers who can exploit software vulnerabilities at scale.