lambdajson-js 1.1.7 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -5,13 +5,21 @@ LambdaJSON is a JSON based pure functional programming language: [https://github
5
5
  ## Quick start
6
6
 
7
7
  ```js
8
- import { compile } from 'lambdajson-js';
8
+ import { compile, lint } from 'lambdajson-js';
9
9
 
10
10
  const program = {
11
- $sum: ['#', 2]
11
+ $map: {
12
+ over: '#.lines',
13
+ as: 'line',
14
+ fn: { $str: ['@line.name', ' x', { $multiply: ['@line.quantity', '#.factor'] }] }
15
+ }
12
16
  };
13
17
  const f = compile(program);
14
18
 
15
- console.log(f(1)); // => 3
19
+ console.log(f({ factor: 2, lines: [{ name: 'bolt', quantity: 3 }] })); // => ['bolt x6']
20
+
21
+ lint({ $str: ['\\ needless escape'] }); // => [{ severity: 'warning', code: 'needless-escape', … }]
16
22
  ```
17
23
 
24
+ `compile` throws a `LambdaJSONError` (with `code` and a JSON Pointer `path`) for a malformed program.
25
+ See the language documentation for the full reference and the migration notes from 1.x.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lambdajson-js",
3
- "version": "1.1.7",
3
+ "version": "2.0.0",
4
4
  "description": "LambdaJSON to JavaScript function compiler",
5
5
  "type": "module",
6
6
  "main": "./src/js-compiler.js",
@@ -1,97 +1,220 @@
1
- import { isObject, isString, map, get, find, mapValues, isArray, every, has } from 'lodash-es'
1
+ import { get, isArray, isPlainObject, isString, map, mapValues } from 'lodash-es'
2
2
  import { primitives } from './primitives.js';
3
3
 
4
4
  export {
5
- compile
5
+ compile,
6
+ lint,
7
+ LambdaJSONError
6
8
  }
9
+ export { primitives, named, special, call } from './primitives.js';
7
10
 
8
11
  /**
9
- * Converts program written in pure json
10
- * @param {object} program
11
- * @param {object} extendedPrimitives
12
+ * A problem in the structure of a program, found while compiling it.
13
+ * `path` is a JSON Pointer to the offending node, `code` a stable identifier.
14
+ */
15
+ class LambdaJSONError extends Error {
16
+ constructor(code, path, message) {
17
+ super(`${message} (at ${path || '/'})`);
18
+ this.name = 'LambdaJSONError';
19
+ this.code = code;
20
+ this.path = path;
21
+ }
22
+ }
23
+
24
+ const LET = '$let';
25
+ const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_-]*$/;
26
+
27
+ /**
28
+ * Converts a program written in pure JSON into a JavaScript function.
29
+ * Throws a LambdaJSONError when the program is malformed.
30
+ * @param {any} program
31
+ * @param {object} extendedPrimitives
12
32
  * @returns {function}
13
33
  */
14
34
  function compile(program, extendedPrimitives = {}) {
15
- const f = compileTree({ ...primitives, ...extendedPrimitives }, program);
16
- return input => f({input});
35
+ const f = compileProgram(program, extendedPrimitives, () => {});
36
+ return input => f({ input, vars: {} });
37
+ }
38
+
39
+ /**
40
+ * Lists the problems of a program without running it: the structural error
41
+ * that makes `compile` throw (if any) and warnings about needless escapes.
42
+ * @param {any} program
43
+ * @param {object} extendedPrimitives
44
+ * @returns {{ severity: 'error' | 'warning', code: string, path: string, message: string }[]}
45
+ */
46
+ function lint(program, extendedPrimitives = {}) {
47
+ const problems = [];
48
+ const warn = (code, path, message) => problems.push({ severity: 'warning', code, path, message });
49
+ try {
50
+ compileProgram(program, extendedPrimitives, warn);
51
+ } catch (error) {
52
+ if (!(error instanceof LambdaJSONError)) throw error;
53
+ problems.push({ severity: 'error', code: error.code, path: error.path, message: error.message });
54
+ }
55
+ return problems;
56
+ }
57
+
58
+ function compileProgram(program, extendedPrimitives, warn) {
59
+ const scope = {
60
+ primitives: { ...primitives, ...extendedPrimitives },
61
+ functions: new Set(),
62
+ warn
63
+ };
64
+ return compileTree(scope, program, '');
17
65
  }
18
66
 
19
- function compileTree(primitives, tree) {
20
- if (isString(tree)) { return compileString(tree); }
67
+ const pointer = (path, key) => `${path}/${String(key).replace(/~/g, '~0').replace(/\//g, '~1')}`;
21
68
 
22
- if (isArray(tree)) { return compileArray(primitives, tree) }
69
+ const fail = (code, path, message) => { throw new LambdaJSONError(code, path, message); };
23
70
 
24
- if (isObject(tree)) {
25
- return isPrimitive(primitives, tree) ? compilePrimitive(primitives, tree) :
26
- isFunction(tree) ? compileFunction(primitives, tree) : compileObject(primitives, tree);
71
+ function compileTree(scope, tree, path) {
72
+ if (isString(tree)) { return compileString(scope, tree, path); }
73
+
74
+ if (isArray(tree)) { return compileArray(scope, tree, path); }
75
+
76
+ if (isPlainObject(tree)) {
77
+ return Object.keys(tree).some(k => k.startsWith('$'))
78
+ ? compileCall(scope, tree, path)
79
+ : compileObject(scope, tree, path);
27
80
  }
28
81
 
29
82
  return () => tree;
30
83
  }
31
84
 
32
- const varsDeclarationKey = '$let';
33
- const valueDeclarationKey = '$literal';
85
+ /**
86
+ * Every object with a `$` key is a call: exactly one call key, optionally beside `$let`.
87
+ */
88
+ function compileCall(scope, tree, path) {
89
+ const keys = Object.keys(tree);
90
+ const data = keys.filter(k => !k.startsWith('$'));
91
+ if (data.length > 0) {
92
+ const call = keys.find(k => k.startsWith('$'));
93
+ fail('mixed-call', path,
94
+ `'${call}' makes this object a call, so '${data.join("', '")}' can't stand beside it; ` +
95
+ `escape the key as '\\${call}' for a plain object`);
96
+ }
97
+
98
+ const calls = keys.filter(k => k !== LET);
99
+ if (calls.length === 0) fail('missing-body', path, `'${LET}' needs a call beside it`);
100
+ if (calls.length > 1) fail('several-calls', path, `one call per object, found '${calls.join("', '")}'`);
101
+ const key = calls[0];
34
102
 
35
- function compilePrimitive(primitives, tree) {
36
- if (has(tree, valueDeclarationKey)) {
37
- return _ => tree[valueDeclarationKey];
103
+ if (!keys.includes(LET)) {
104
+ return compileHead(scope, key, tree[key], path);
38
105
  }
39
- const keys = Object.keys(tree);
40
- const getLocalVars = compileVars(primitives, tree[varsDeclarationKey]);
41
- const primitiveKey = find(keys, k => k !== varsDeclarationKey);
42
- const f = primitives[primitiveKey](parsePrimitiveArgs(primitives, tree[primitiveKey]));
106
+
107
+ const declarations = tree[LET];
108
+ const letPath = pointer(path, LET);
109
+ if (!isPlainObject(declarations)) fail('invalid-let', letPath, `'${LET}' is an object of declarations`);
110
+ const inner = { ...scope, functions: new Set(scope.functions) };
111
+ for (const name of Object.keys(declarations)) {
112
+ if (name.startsWith('$')) {
113
+ if (scope.primitives[name] !== undefined) fail('shadowed-primitive', pointer(letPath, name), `'${name}' is a primitive and can't be redeclared`);
114
+ inner.functions.add(name);
115
+ }
116
+ }
117
+ const getLocalVars = compileVars(inner, declarations, letPath);
118
+ const f = compileHead(inner, key, tree[key], path);
43
119
  return ({ vars, input }) => {
44
120
  const extendedVars = { ...vars, ...getLocalVars({ vars, input }) };
45
121
  return f({ vars: extendedVars, input });
122
+ };
123
+ }
124
+
125
+ function compileHead(scope, key, value, path) {
126
+ const argPath = pointer(path, key);
127
+ const primitive = scope.primitives[key];
128
+ if (primitive !== undefined) {
129
+ return compilePrimitive(scope, key, primitive, value, argPath);
130
+ }
131
+ if (scope.functions.has(key)) {
132
+ return compileFunctionCall(scope, key, value, argPath);
46
133
  }
134
+ return fail('unknown-function', argPath, `unknown function '${key}': neither a primitive nor declared in an enclosing '${LET}'`);
47
135
  }
48
136
 
49
- function compileFunction(primitives, tree) {
50
- const keys = Object.keys(tree);
51
- const getLocalVars = compileVars(primitives, tree[varsDeclarationKey]);
52
- const functionKey = find(keys, k => k !== varsDeclarationKey);
53
- const arg = compileTree(primitives, tree[functionKey]);
54
- return ({ vars, input }) => {
55
- const extendedVars = { ...vars, ...getLocalVars({ vars, input }) };
56
- const f = extendedVars[functionKey];
57
- return f({ vars: extendedVars, input: arg({ vars: extendedVars, input })});
137
+ function compilePrimitive(scope, key, primitive, value, path) {
138
+ if (typeof primitive === 'function') {
139
+ return primitive(compileTree(scope, value, path));
140
+ }
141
+ if (primitive.special) {
142
+ return primitive.special(value, specialContext(scope, key, path));
143
+ }
144
+ if (primitive.params) {
145
+ return primitive.impl(compileNamedArgs(scope, key, primitive.params, value, path));
58
146
  }
147
+ return fail('invalid-primitive', path, `primitive '${key}' is neither a function nor a { params, impl } or { special } descriptor`);
59
148
  }
60
149
 
61
- function parsePrimitiveArgs(primitives, tree) {
62
- if (isString(tree)) { return compileString(tree); }
150
+ function specialContext(scope, key, path) {
151
+ return {
152
+ compile: (tree, ...steps) => compileTree(scope, tree, steps.reduce(pointer, path)),
153
+ fail: (message, ...steps) => fail('invalid-arguments', steps.reduce(pointer, path), `${key}: ${message}`),
154
+ warn: (code, message, ...steps) => scope.warn(code, steps.reduce(pointer, path), message),
155
+ path
156
+ };
157
+ }
63
158
 
64
- if (isArray(tree)) { return compileArray(primitives, tree) }
159
+ /**
160
+ * Parameters are declared as names: `fn` is required, `over=#` defaults to the input,
161
+ * `as?` is optional. The parameter `as` is syntax: the names bound to a lambda's arguments.
162
+ */
163
+ function parseParams(params) {
164
+ return params.map(spec => {
165
+ const name = spec.replace(/(=#|\?)$/, '');
166
+ return { name, required: spec === name, defaultsToInput: spec.endsWith('=#') };
167
+ });
168
+ }
65
169
 
66
- if (isObject(tree)) {
67
- return hasPrimitiveProperties(tree) ? mapValues(tree, n => compileTree(primitives, n)) : compileTree(primitives, tree);
68
- }
170
+ const inputParam = ({ input }) => input;
69
171
 
70
- return () => tree;
71
- }
172
+ function compileNamedArgs(scope, key, params, value, path) {
173
+ const declared = parseParams(params);
174
+ const names = declared.map(p => p.name);
175
+ const expected = `{ ${params.join(', ')} }`;
176
+ if (!isPlainObject(value) || Object.keys(value).some(k => k.startsWith('$'))) {
177
+ fail('named-arguments-expected', path, `'${key}' takes named arguments ${expected}`);
178
+ }
72
179
 
73
- function isPrimitive(primitives, tree) {
74
- const ks = Object.keys(tree);
75
- return ks.length > 0 && ks.length <= 2 && every(ks, k => !!primitives[k]);
180
+ const args = {};
181
+ for (const [k, v] of Object.entries(value)) {
182
+ const argPath = pointer(path, k);
183
+ if (!names.includes(k)) {
184
+ const hint = k.startsWith('_') && names.includes(k.slice(1)) ? ` (write '${k.slice(1)}': parameters have no '_' prefix since version 2)` : '';
185
+ fail('unknown-parameter', argPath, `'${key}' has no parameter '${k}', expected ${expected}${hint}`);
186
+ }
187
+ args[k] = k === 'as' ? parseAs(v, argPath) : compileTree(scope, v, argPath);
188
+ }
189
+ for (const p of declared) {
190
+ if (p.name in args) continue;
191
+ if (p.required) fail('missing-parameter', path, `'${key}' requires '${p.name}', expected ${expected}`);
192
+ if (p.defaultsToInput) args[p.name] = inputParam;
193
+ }
194
+ return args;
76
195
  }
77
196
 
78
- function isFunction(tree) {
79
- const ks = Object.keys(tree);
80
- return ks.length > 0 && ks.length <= 2 && every(ks, k => k.startsWith('$'));
197
+ function parseAs(value, path) {
198
+ const names = isArray(value) ? value : [value];
199
+ if (names.length === 0 || !names.every(n => isString(n) && IDENTIFIER.test(n))) {
200
+ fail('invalid-as', path, `'as' is a name or an array of names, e.g. "item" or ["total", "item"]`);
201
+ }
202
+ return names;
81
203
  }
82
204
 
83
- function hasPrimitiveProperties(tree) {
84
- return Object.keys(tree)[0]?.startsWith('_');
205
+ function compileFunctionCall(scope, key, value, path) {
206
+ const arg = compileTree(scope, value, path);
207
+ return ({ vars, input }) => vars[key]({ vars, input: arg({ vars, input }) });
85
208
  }
86
209
 
87
- function compileArray(primitives, tree) {
88
- const funks = map(tree, n => compileTree(primitives, n), primitives);
210
+ function compileArray(scope, tree, path) {
211
+ const funks = map(tree, (n, i) => compileTree(scope, n, pointer(path, i)));
89
212
  return x => map(funks, f => f(x));
90
213
  }
91
214
 
92
- function compileVars(primitives, obj) {
93
- const funks = mapValues(obj, n => compileTree(primitives, n));
94
- return ({vars, input}) => {
215
+ function compileVars(scope, obj, path) {
216
+ const funks = mapValues(obj, (n, k) => compileTree(scope, n, pointer(path, k)));
217
+ return ({ vars, input }) => {
95
218
  const localVars = {};
96
219
  const extendedVars = { ...vars };
97
220
  for (const key in funks) {
@@ -101,38 +224,44 @@ function compileVars(primitives, obj) {
101
224
  extendedVars[key] = localVars[key];
102
225
  }
103
226
  return localVars;
104
- }
227
+ };
105
228
  }
106
229
 
107
- function compileObject(primitives, obj) {
108
- const funks = mapValues(obj, n => compileTree(primitives, n));
109
- return x => {
110
- const result = {};
111
- for (const key in funks) {
112
- const pKey = key.startsWith('\\') ? key.slice(1) : key;
113
- result[pKey] = funks[key](x);
230
+ function compileObject(scope, obj, path) {
231
+ const funks = {};
232
+ for (const key of Object.keys(obj)) {
233
+ let outKey = key;
234
+ if (key.startsWith('\\')) {
235
+ outKey = key.slice(1);
236
+ if (!outKey.startsWith('$') && !outKey.startsWith('\\')) {
237
+ scope.warn('needless-escape', pointer(path, key), `the key '${outKey}' needs no escape`);
238
+ }
114
239
  }
115
- return result;
116
- };
240
+ funks[outKey] = compileTree(scope, obj[key], pointer(path, key));
241
+ }
242
+ return x => mapValues(funks, f => f(x));
117
243
  }
118
244
 
119
- function compileString(str) {
245
+ function compileString(scope, str, path) {
120
246
  if (str.startsWith('\\')) {
121
- return () => str.slice(1);
247
+ const value = str.slice(1);
248
+ if (!/^[#@\\]/.test(value)) {
249
+ scope.warn('needless-escape', path, `the string '${value}' needs no escape`);
250
+ }
251
+ return () => value;
122
252
  }
123
253
  if (str === '#') {
124
254
  return ({ input }) => input;
125
255
  }
126
256
  if (str.startsWith('#')) {
127
- str = str.slice(1);
128
- str = /^\d/.test(str) ? `[${str[0]}]` + str.slice(1) : str;
129
- str = str.startsWith('.') ? str.slice(1) : str;
130
- const pointer = str;
131
- return ({ input }) => get(input, pointer);
257
+ let p = str.slice(1);
258
+ p = /^\d/.test(p) ? `[${p[0]}]` + p.slice(1) : p;
259
+ p = p.startsWith('.') ? p.slice(1) : p;
260
+ return ({ input }) => get(input, p);
132
261
  }
133
262
  if (str.startsWith('@')) {
134
- const pointer = str.slice(1);
135
- return ({ vars }) => get(vars, pointer);
263
+ const p = str.slice(1);
264
+ return ({ vars }) => get(vars, p);
136
265
  }
137
266
  return () => str;
138
267
  }
package/src/primitives.js CHANGED
@@ -1,73 +1,141 @@
1
1
  import { printf } from 'fast-printf';
2
- import { concat, divide, eq, every, filter, first, get, groupBy, gt, gte, includes, join, keyBy, keys, lt, lte, map, mapValues, merge, multiply,
3
- reduce, some, split, subtract, sum, tail, take, takeWhile, values, zipWith } from 'lodash-es'
2
+ import { concat, divide, eq, every, filter, first, get, groupBy, gt, gte, includes, isArray, join, keyBy, keys, lt, lte, map, mapValues, merge, multiply,
3
+ orderBy, reduce, some, split, subtract, sum, tail, take, takeWhile, values, zipObject, zipWith } from 'lodash-es'
4
4
 
5
- const input = ({ input }) => input
5
+ /**
6
+ * Primitives come in three shapes:
7
+ * - a function `f => x => …`: the argument is compiled as one expression `f` (positional);
8
+ * - `{ params, impl }`: named arguments, `params` lists them (`fn` required, `over=#` defaults
9
+ * to the input, `as?` optional); `impl` receives an object of compiled arguments;
10
+ * - `{ special }`: a special form, `special(rawArgument, context)` compiles what it needs itself.
11
+ */
12
+ export const named = (params, impl, extra = {}) => ({ params, impl, ...extra });
13
+ export const special = (form, extra = {}) => ({ special: form, ...extra });
14
+
15
+ /**
16
+ * Calls a compiled lambda with the arguments of a callback. Without `as` the lambda's input `#`
17
+ * is `input` (by default the first argument); with `as` the arguments are bound to the names
18
+ * (read as `@name`) and `#` stays the input of the enclosing expression.
19
+ */
20
+ export const call = (fn, as, x, args, input = args[0]) => as === undefined
21
+ ? fn({ ...x, input })
22
+ : fn({ ...x, vars: { ...x.vars, ...zipObject(as, args) } });
23
+
24
+ const lambda = (fn, as, x) => (...args) => call(fn, as, x, args);
25
+
26
+ const toStr = v => v == null ? '' : typeof v === 'object' ? JSON.stringify(v) : String(v);
27
+
28
+ const variadic = (name, empty, decides) => special((args, { compile }) => {
29
+ if (!isArray(args)) {
30
+ const f = compile(args);
31
+ return x => {
32
+ const vs = f(x);
33
+ return vs.length === 0 ? empty : vs.find(decides) ?? vs[vs.length - 1];
34
+ };
35
+ }
36
+ const fs = args.map((a, i) => compile(a, i));
37
+ return x => {
38
+ let v = empty;
39
+ for (const f of fs) {
40
+ v = f(x);
41
+ if (decides(v)) return v;
42
+ }
43
+ return v;
44
+ };
45
+ }, { description: `${name}: [a, b, …], short-circuits` });
46
+
47
+ const sort = direction => named(['by?', 'collection=#', 'as?'], ({ by, collection, as }) => x =>
48
+ orderBy(collection(x), by ? [v => call(by, as, x, [v])] : undefined, [direction]));
6
49
 
7
50
  export const primitives = {
8
51
  $let: true,
9
- $literal: true,
10
- $: f => x => v => f({ ...x, input: v}),
52
+ $literal: special(value => () => value),
53
+ $: f => x => v => f({ ...x, input: v }),
11
54
  $in: f => x => f(x),
12
55
  $return: f => x => f(x),
13
- $apply: ({ _fn, _to = input }) => x => _fn({ ...x, input: _to(x)}),
56
+ $apply: named(['fn', 'to=#', 'as?'], ({ fn, to, as }) => x => call(fn, as, x, [to(x)])),
14
57
  $pipeline: f => x => reduce(f(x), (a, g) => g(a), x.input),
15
- $conditional: ({ _if, _then, _else }) => x => _if(x) ? _then(x) : _else(x),
58
+
59
+ $if: special((args, { compile, fail }) => {
60
+ if (!isArray(args) || args.length < 2 || args.length > 3) fail('takes [test, then] or [test, then, else]');
61
+ const [test, then, otherwise] = args.map((a, i) => compile(a, i));
62
+ return x => test(x) ? then(x) : otherwise ? otherwise(x) : null;
63
+ }),
64
+ $cond: special((args, { compile, fail }) => {
65
+ if (!isArray(args) || !args.every(c => isArray(c) && c.length === 2)) {
66
+ fail('takes clauses [[test, value], …]; a last clause ["else", value] always matches');
67
+ }
68
+ const clauses = args.map((c, i) => [compile(c[0], i, 0), compile(c[1], i, 1)]);
69
+ return x => {
70
+ for (const [test, value] of clauses) {
71
+ if (test(x)) return value(x);
72
+ }
73
+ return null;
74
+ };
75
+ }),
76
+ $and: variadic('$and', true, v => !v),
77
+ $or: variadic('$or', false, v => !!v),
78
+ $not: f => x => !f(x),
79
+ $negate: f => x => !f(x),
80
+
16
81
  $eq: f => x => eq(...f(x)),
17
82
  $neq: f => x => !eq(...f(x)),
18
- $negate: f => x => !f(x),
19
83
  $lt: f => x => lt(...f(x)),
20
84
  $lte: f => x => lte(...f(x)),
21
85
  $gt: f => x => gt(...f(x)),
22
86
  $gte: f => x => gte(...f(x)),
23
- $map: ({ _fn, _over = input }) => x => map(_over(x), v => _fn({ ...x, input: v })),
24
- $mapValues: ({ _fn, _of = input }) => x => mapValues(_of(x), v => _fn({ ...x, input: v })),
87
+
25
88
  $sum: f => x => sum(f(x)),
26
89
  $subtract: f => x => subtract(...f(x)),
27
90
  $multiply: f => x => multiply(...f(x)),
28
91
  $divide: f => x => divide(...f(x)),
29
- $filter: ({ _predicate, _collection = input }) => x => filter(_collection(x), v => _predicate({ ...x, input: v })),
92
+
93
+ $map: named(['fn', 'over=#', 'as?'], ({ fn, over, as }) => x => map(over(x), lambda(fn, as, x))),
94
+ $mapValues: named(['fn', 'of=#', 'as?'], ({ fn, of, as }) => x => mapValues(of(x), lambda(fn, as, x))),
95
+ $filter: named(['predicate', 'collection=#', 'as?'], ({ predicate, collection, as }) => x => filter(collection(x), lambda(predicate, as, x))),
96
+ $any: named(['predicate', 'collection=#', 'as?'], ({ predicate, collection, as }) => x => some(collection(x), lambda(predicate, as, x))),
97
+ $all: named(['predicate', 'collection=#', 'as?'], ({ predicate, collection, as }) => x => every(collection(x), lambda(predicate, as, x))),
98
+ $group: named(['by', 'collection=#', 'as?'], ({ by, collection, as }) => x => groupBy(collection(x), v => call(by, as, x, [v]))),
99
+ $toDictionary: named(['by', 'collection=#', 'as?'], ({ by, collection, as }) => x => keyBy(collection(x), v => call(by, as, x, [v]))),
100
+ $take: named(['while?', 'count?', 'from=#', 'as?'], ({ while: whileFn, count, from, as }) => x => {
101
+ let y = from(x);
102
+ y = whileFn ? takeWhile(y, v => call(whileFn, as, x, [v])) : y;
103
+ y = count ? take(y, count(x)) : y;
104
+ return y;
105
+ }),
106
+ $zip: named(['with?', 'sequences=#', 'as?'], ({ with: withFn, sequences, as }) => x => {
107
+ const [as_, bs] = sequences(x);
108
+ return zipWith(as_, bs, (a, b) => withFn ? call(withFn, as, x, [a, b], [a, b]) : [a, b]);
109
+ }),
110
+ $fold: named(['with', 'init?', 'collection=#', 'as?'], ({ with: withFn, init, collection, as }) => {
111
+ const step = x => (a, v) => call(withFn, as, x, [a, v], [a, v]);
112
+ return init
113
+ ? x => reduce(collection(x), step(x), init(x))
114
+ : x => reduce(collection(x), step(x));
115
+ }),
116
+ $ascending: sort('asc'),
117
+ $descending: sort('desc'),
118
+
30
119
  $head: f => x => first(f(x)),
31
120
  $tail: f => x => tail(f(x)),
32
121
  $concat: f => x => concat(...f(x)),
33
- $group: ({ _by, _collection = input }) => x => groupBy(_collection(x), v => _by({...x, input: v})),
34
- $toDictionary: ({ _by, _collection = input }) => x => keyBy(_collection(x), v => _by({...x, input: v})),
35
122
  $keys: f => x => keys(f(x)),
123
+ $values: f => x => values(f(x)),
36
124
  $merge: f => x => merge({}, ...f(x)),
37
125
  $coalesce: f => x => f(x).find(v => v != null),
38
- $any: ({ _collection = input, _predicate }) => x => some(_collection(x), v => _predicate({ ...x, input: v })),
39
- $all: ({ _collection = input, _predicate }) => x => every(_collection(x), v => _predicate({ ...x, input: v })),
40
- $values: f => x => values(f(x)),
41
- $get: ({ _object = input, _path }) => x => get(_object(x), _path(x)),
42
- $includes: ({ _collection = input, _value }) => x => includes(_collection(x), _value(x)),
43
- $split: ({ _separator, _string = input }) => x => split(_string(x), _separator(x)),
44
- $match: ({ _pattern, _string = input }) => x => _string(x).match(_pattern(x)),
45
- $join: ({ _separator = _ => "", _strings = input }) => x => join(_strings(x), _separator(x)),
46
- $printf: ({ _template, _args = input}) => x => printf(_template(x), ..._args(x)),
47
- $take: ({ _while, _count, _from = input }) => x => {
48
- let y = _from(x);
49
- y = _while ? takeWhile(y, v => _while({ ...x, input: v })) : y
50
- y = _count ? take(y, _count(x)) : y
51
- return y;
52
- },
53
- $zip: ({ _with, _sequences = input }) => {
54
- const combinator = _with ? (x, v) => _with({...x, input: v}) : (x, v) => v;
55
- return x => {
56
- const [as, bs] = _sequences(x);
57
- return zipWith(as, bs, (a, b) => combinator(x, [a, b]));
58
- }
59
- },
60
- $fold: ({ _with, _init, _collection = input }) => {
61
- const aggregator = (x, v) => _with({...x, input: v});
62
- return _init
63
- ? x => reduce(_collection(x), (a, v) => aggregator(x, [a, v]), _init(x))
64
- : x => reduce(_collection(x), (a, v) => aggregator(x, [a, v]));
65
- },
66
- $replace: ({ _regex, _substitute, _string = input, _global }) => x => {
67
- const pattern = _global?.(x) ? new RegExp(_regex(x), 'g') : _regex(x);
68
- return _string(x).replace(pattern, _substitute(x));
69
- },
70
- $isMatch: ({ _pattern, _string = input }) => x => new RegExp(_pattern(x)).test(_string(x)),
126
+ $get: named(['object=#', 'path'], ({ object, path }) => x => get(object(x), path(x))),
127
+ $includes: named(['collection=#', 'value'], ({ collection, value }) => x => includes(collection(x), value(x))),
128
+
129
+ $str: f => x => { const v = f(x); return isArray(v) ? v.map(toStr).join('') : toStr(v); },
130
+ $join: named(['separator?', 'strings=#'], ({ separator = () => '', strings }) => x => join(strings(x), separator(x))),
131
+ $split: named(['separator', 'string=#'], ({ separator, string }) => x => split(string(x), separator(x))),
132
+ $match: named(['pattern', 'string=#'], ({ pattern, string }) => x => string(x).match(pattern(x))),
133
+ $isMatch: named(['pattern', 'string=#'], ({ pattern, string }) => x => new RegExp(pattern(x)).test(string(x))),
134
+ $replace: named(['regex', 'substitute', 'string=#', 'global?'], ({ regex, substitute, string, global }) => x => {
135
+ const p = global?.(x) ? new RegExp(regex(x), 'g') : regex(x);
136
+ return string(x).replace(p, substitute(x));
137
+ }),
138
+ $printf: named(['template', 'args=#'], ({ template, args }) => x => printf(template(x), ...args(x))),
71
139
  $parseInt: f => x => { const n = parseInt(f(x), 10); return isNaN(n) ? undefined : n; },
72
140
  $parseFloat: f => x => { const n = parseFloat(f(x)); return isNaN(n) ? undefined : n; },
73
141
  }