UNPKG

mikel-eval

Version:

A mikel plugin for evaluating JavaScript expressions.

213 lines (125 loc) 5.74 kB
# mikel-eval ![npm version](https://badgen.net/npm/v/mikel-eval?labelColor=1d2734&color=21bf81) ![license](https://badgen.net/github/license/jmjuanes/mikel?labelColor=1d2734&color=21bf81) The `mikel-eval` plugin extends the [mikel](https://github.com/jmjuanes/mikel) templating engine with expression evaluation capabilities. It allows you to evaluate mathematical, string, boolean, and array expressions directly within your templates. ## Installation Install the plugin using **npm** or **yarn**: ```bash # Using npm npm install mikel-eval # Using yarn yarn add mikel-eval ``` ## Usage Import and register the plugin with Mikel: ```javascript import mikel from "mikel"; import mikelEval from "mikel-eval"; // 1. create a new mikel instance for the given template const m = mikel.create(`{{x}} * 2 = {{=eval "x * 2"}}`); // 2. register the plugin m.use(mikelEval()); // 3. render the template with the provided data context console.log(m({x: 5})); // --> "5 * 2 = 10" ``` You can also use this plugin with the default instance of Mikel: ```javascript import mikel from "mikel"; import mikelEval from "mikel-eval"; // 1. get the options generated by mikelEval const options = mikelEval(); // 2. render the template with the default instance of mikel console.log(mikel(`{{=eval "1 + 2"}}`, {}, options)); // --> "3" ``` ## Features Supported expressions: - **Math:** `+`, `-`, `*`, `/`, `%`, `^`, and parentheses. - **Strings:** Concatenation with `+` and string functions. - **Booleans:** logical operators (`&&`, `||`, `!`) and comparisons (`==`, `!=`, `<`, `>`, `<=`, `>=`). - **Arrays:** Array functions like `len`, `indexOf`, `join`, `in`. - **Functions:** Built-in functions such as `abs`, `sqrt`, `max`, `min`, `replace`, `toUpperCase`, etc. ## Built-in Functions The following functions are available by default in expressions evaluated by mikel-eval: ### Common Functions #### `len(x)` Returns the length of a string, array, or the number of keys in an object. Examples: `len([1,2,3])``3`, `len("abc")``3`. #### `in(x, item)` Checks if `item` is present in array, string, or object values. Examples: `in([1,2,3], 2)``true`, `in("hello", "ll")``true`. #### `type(x)` Returns the JavaScript type of the provided argument as a string. Examples: `type(123)``"number"`, `type("abc")``"string"`. #### `if(condition, trueValue, falseValue)` Returns `trueValue` if `condition` is `true`, otherwise returns `falseValue`. Example: `if(1 < 2, "yes", "no")``"yes"`. ### Array Functions #### `indexOf(array, item)` Returns the index of `item` in `array`, or `-1` if not found. Example: `indexOf([1,2,3], 2)``1`. #### `join(array, separator)` Joins array elements into a string, separated by `separator` (default: `","`). Example: `join([1,2,3], "-")``"1-2-3"`. ### Object Functions #### `valueOf(obj, key)` Returns the value of `obj[key]`. Example: `valueOf(myObject, "b")`. ### String Functions #### `startsWith(str, prefix)` Returns `true` if `str` starts with `prefix`. Example: `startsWith("hello", "he")``true`. #### `endsWith(str, suffix)` Returns `true` if `str` ends with `suffix`. Example: `endsWith("hello", "lo")``true`. #### `replace(str, search, replacement)` Replaces all occurrences of `search` in `str` with `replacement`. Example: `replace("foo bar", "bar", "baz")``"foo baz"`. #### `toUpperCase(str)` Converts `str` to uppercase. Example: `toUpperCase("abc")``"ABC"`. #### `toLowerCase(str)` Converts `str` to lowercase. Example: `toLowerCase("ABC")``"abc"`. #### `trim(str)` Removes whitespace from both ends of `str`. Example: `trim(" hello ")``"hello"`. ### Mathematical Functions #### `min(...args)` Returns the smallest of the provided numbers. Example: `min(1, 2, 3)``1`. #### `max(...args)` Returns the largest of the provided numbers. Example: `max(1, 2, 3)``3`. #### `abs(x)` Returns the absolute value of `x`. Example: `abs(-5)``5`. #### `round(x)` Rounds `x` to the nearest integer. Example: `round(2.5)``3`. #### `ceil(x)` Rounds `x` up to the next largest integer. Example: `ceil(2.1)``3`. #### `floor(x)` Rounds `x` down to the next smallest integer. Example: `floor(2.9)``2`. #### `sqrt(x)` Returns the square root of `x`. Example: `sqrt(16)``4`. #### `pow(x, y)` Returns `x` raised to the power of `y`. Example: `pow(2, 3)``8`. #### `random()` Returns a random number between 0 (inclusive) and 1 (exclusive). Example: `random()``0.123456...`. ## API ### `=eval` function Evaluates the given expression and prints the result. ```javascript m(`{{=eval "1 + 2"}}`, {}); // Output: "3" ``` You can use variables from your data context: ```javascript m(`{{=eval "'Hello ' + name"}}`, { name: "World" }); // Output: "Hello World" m(`{{=eval "x * y"}}`, { x: 2, y: 3 }); // Output: "6" ``` ### `#when` helper Renders the block only if the evaluated expression is `true`. ```javascript m(`{{#when "x > 1"}}x is greater than 1{{/when}}`, { x: 2 }); // Output: "x is greater than 1" m(`{{#when "'foo' == 'bar'"}}This will not render{{/when}}`, {}); // Output: "" ``` You use variables from your data context: ```javascript m(`{{#when "x > 1"}}x is greater than 1{{/when}}`, { x: 2 }); // Output: "x is greater than 1" m(`{{#when "x < 1"}}x is less than 1{{/when}}`, { x: 2 }); // Output: "" ``` ## Custom Functions You can provide your own functions via the plugin options: ```javascript const options = mikelEval({ functions: { double: x => x * 2, }, })); console.log(mikel(`{{=eval "double(5)"}}`, {}, options)); // Output: "10" ``` ## License Licensed under the [MIT License](../../LICENSE).