Blog/wwwroot/jsonql-js/functions.js 981 B · 27 lines · raw · history

1 import { SqlEvaluationError } from './errors.js';
2
3 /**
4 * Builtin functions callable from expressions, keyed by uppercase name.
5 * Extend/override at call time via `evaluate(ast, ctx, { functions })`.
6 * @type {Record<string, (...args: any[]) => any>}
7 */
8 export const builtins = {
9 LOWER: (v) => (v === null || v === undefined ? null : String(v).toLowerCase()),
10 UPPER: (v) => (v === null || v === undefined ? null : String(v).toUpperCase()),
11 LENGTH: (v) => {
12 if (v === null || v === undefined) return null;
13 if (typeof v === 'string' || Array.isArray(v)) return v.length;
14 throw new SqlEvaluationError('LENGTH requires a string or array');
15 },
16 ABS: (v) => {
17 if (v === null || v === undefined) return null;
18 if (typeof v !== 'number') throw new SqlEvaluationError('ABS requires a number');
19 return Math.abs(v);
20 },
21 COALESCE: (...args) => {
22 for (const a of args) {
23 if (a !== null && a !== undefined) return a;
24 }
25 return null;
26 },
27 };