@comyata/run
Version:
Simplify data workflows and management with data templates, for browser and server.
39 lines • 1 kB
JavaScript
import jsonata from 'jsonata';
export function toExpr(expr, functions = jsonataExtraFunctions) {
const exprEval = jsonata(expr, {
recover: false
});
exprEval.registerFunction('coalesce', (...args) => args.find(arg => typeof arg !== 'undefined' && arg !== null));
for (const fn of functions) {
exprEval.registerFunction(fn.name, fn.fn, fn.signature);
}
return exprEval;
}
export const jsonataExtraFunctions = [{
name: 'repeat',
fn: (str, count) => str.repeat(count),
signature: '<sn:s>'
}, {
name: 'some',
fn: async function (arr, test) {
if (!arr) return false;
for (const item of arr) {
const r = await test.apply(this, [item]);
if (r) return true;
}
return false;
},
signature: '<(al)f:b>'
}, {
name: 'toJSON',
fn: value => JSON.stringify(value),
signature: '<j:s>'
}, {
name: 'fromJSON',
fn: text => JSON.parse(text),
signature: '<s:j>'
}, {
name: 'isNaN',
fn: text => Number.isNaN(Number(text)),
signature: '<(sn):b>'
}];