zookd

0.2.3 • Public • Published

zookd

An expression language that is compiled to JavaScript.

The lexer and parser are greatly inspired by CoffeeScript.

Syntax

Null

Represents null in JavaScript.

zookd.eval('null'); // => null

Identifier

  1. Identifiers may only include the following characters: letters ('a'..'z', 'A'..'Z'), digits ('0'..'9'), underscores ('_') and dollar signs ('$').
  2. The first character must not be a digit.
  3. The identifier must not be one of the keywords (such as null).

All the identifiers should be declared in the context.

zookd.eval.call({ foo: 'bar' }, 'foo'); // => 'bar'
zookd.eval.call({ 'if': 42 }, 'if'); // => 42

Literal

In zookd, there are 5 types of literals: Numbers, Booleans, Strings, Lists and Maps.

Number Literal

Number literals are decimal numbers.

zookd.eval('1'); // => 1
zookd.eval('2.'); // => 2
zookd.eval('-.5'); // => -0.5
zookd.eval('-0'); // => -0
zookd.eval('1 / 2'); // => 0.5
zookd.eval('3 * (4 + 5)'); // => 27
zookd.eval('-1 / 0'); // => -Infinity
zookd.eval('~-1'); // => 0
zookd.eval('1 & 3'); // => 1
zookd.eval('1 ^ 3'); // => 2
zookd.eval('1 | 3'); // => 3

Boolean Literal

Boolean literals represent true or false.

zookd.eval('!false && false || true'); // => true
zookd.eval('!!false'); // => false

String Literal

String literals represent strings.

zookd.eval('"zoo" + "kd"'); // => 'zookd'

List Literal

List literals represent arrays in JavaScript.

Note that trailing comma and empty element are not allowed in zookd.

zookd.eval('[ [ 1, 2 ], "foobar" ]'); // => [ [ 1, 2 ], 'foobar' ]

Map Literal

List literals represent plain objects in JavaScripts.

zookd.eval('{ foo: { "bar": [ "baz" ] } }'); // => { foo: { "bar": [ "baz" ] } }

Lambda Expression

Lambda expressions are anonymous functions that transform some values to another ones.

let ctx = { map: (target, fn) => target.map(fn) };
zookd.eval.call(ctx, 'map(map([ 1, 1, 1 ], (val, index) => index + 1), val => val * 2)');
// => [ 2, 4, 6 ]

Property Accessors

Properties can be accessed with dot notations or bracket notations.

let ctx = { foo: { bar: { baz: [ 10, 42 ] } } };
zookd.eval.call(ctx, 'foo.bar["baz"][foo["bar"].baz.length - 1]'); // => 42

Function Call

A function in the top level of the context can be called.

let ctx = {
  sum: numbers => numbers.reduce((a, b) => a + b, 0)
};
zookd.eval.call(ctx, 'sum([ 1, 2, 3 ])'); // => 6

API Reference

compile(expression)

Compile an expression to a JavaScript function which returns its value.

let fn = zookd.compile('1 + 2.5');
fn.toString(); // => 'function anonymous() {\nreturn 1 + 2.5;\n}'
fn(); // => '3.5'

eval(expression)

Compile and evaluate the expression.

zookd.eval('"Hello zookd!"'); // => 'Hello zookd!'

Readme

Keywords

none

Package Sidebar

Install

npm i zookd

Weekly Downloads

10

Version

0.2.3

License

MIT

Last publish

Collaborators

  • lujjjh