-
Notifications
You must be signed in to change notification settings - Fork 1
/
fun.js
592 lines (315 loc) · 13.3 KB
/
fun.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
"use strict";
const DEBUG = true;
/* Checks */
const isArr = x => Array.isArray(x);
const isAny = (f, ...v) => reduce((x,y) => x == true || y == true, false, map(f, ...v));
const isEvery = (f, ...v) => reduce((x,y) => x == true && y == true, true, map(f, ...v));
const isDomElem = o => (typeof HTMLElement != "undefined" && o instanceof HTMLElement) || (typeof SVGElement != "undefined" && o instanceof SVGElement);
const isColl = o => isArr(o) || (typeof NodeList != "undefined" && o instanceof NodeList) || (typeof Set != "undefined" && o instanceof Set);
const isObj = o => typeof(o) == "object" && (o != null) && !isColl(o) && !isDomElem(o);
const isEmpty = a => {
if(typeof a == "string" || isArr(a)) return a.length == 0;
else if(isObj(a)) return Object.entries(a).length == 0;
else return a == null || a == undefined;
};
const notEmpty = a => isEmpty(a) ? null : a;
const find = (f,xs) => xs.find((...x) => f(...x)) || null;
/* Math Ops */
const degToRad = x => (x / 180) * Math.PI;
const radToDeg = x => (x * 180) / Math.PI;
/* Vector Operations */
const vAdd = ([x1,y1], [x2,y2]) => [x1 + x2, y1 + y2];
const vSub = ([x1,y1], [x2,y2]) => [x1 - x2, y1 - y2];
const vMul = ([x,y], m) => [x * m, y * m];
const vDiv = ([x,y], m) => [x / m, y / m];
const vRot = ([x,y], angleInDegrees) => {
const angleInRad = degToRad(angleInDegrees);
const cos = Math.cos(angleInRad), sin = Math.sin(angleInRad);
return [x * cos - y * sin, x * sin + y * cos];
};
const vMag = ([x,y]) => Math.hypot(x, y);
/* Divides by 1 incase the vMag is 0. */
const vUnit = v => vDiv(v, vMag(v) || 1);
/* Array Ops */
const head = arr => arr[0];
const tail = arr => arr.slice(1);
const concat = (...arrs) => Array.prototype.concat(...arrs);
const transpose = colls => {
let repetition = colls.length > 0 ? Math.min(...map(x => x.length, colls)) : 0;
if(repetition == 0) return repeat([], colls.length);
let idxs = notEmpty(range(0, (repetition - 1))) || [0];
return map(i => map(x => x[i], colls), idxs);
};
/* Dictionary Ops */
const assoc = (s, k, v) => merge(s, {[k]: v});
const assocAbsent = (x,kvs) => {
const assocOne = (x,k,v) => (k in x) ? x : merge(x,{[k]: v});
return kvreduce((i,k,v) => assocOne(i,k,v), x, kvs);
};
const dissoc = (s, ...props) => reduce((init,next) => (delete init[next],init), merge({},s), props);
const merge = (...x) => Object.assign({},...x);
const update = (s, prop, f, v) => assoc(s,prop,f(s[prop] || {},v));
const selectKeys = (v,keys) => reduce((i,x) => (v[x] == 0 || v[x]) ? merge(i,{[x]: v[x]}) : i,{},keys);
const renameKeys = (m, keymap = {}) => kvreduce((_,k,v) => ((k in m) && (m[v] = m[k], delete m[k]), m), keymap);
/* Random */
const random = (min, max, attrs = {}) => {
if(max == null) { max = min; min = 0; };
let {asInt, seed, count = 1} = attrs;
if(seed == null) seed = Date.now() + Math.random() * 1000000;
const threshold = 2 ** 32;
const rnd = (seed, threshold = 2 ** 32) => {
const distributor = 2 ** 13 + 1;
const prime = 1987;
return ((seed * distributor) + prime) % threshold;
}
let res = [];
let nextSeed = rnd(seed, threshold);
for(let i = 0; i < count; i++) {
let num = rnd(nextSeed);
let normalized = num / threshold;
let val = min + normalized * (max - min);
res.push(asInt ? Math.round(val) : val);
nextSeed = num;
}
return (count == 1) ? res[0] : res;
};
const randomVec = ([startX, startY], [endX, endY], attrs = {}) => {
let [xSeed, ySeed] = random(1991, 4000, {count: 2, seed: attrs && attrs.seed || null, asInt: true});
let xAttrs = Object.assign({count: 1}, attrs, {seed: xSeed});
let yAttrs = Object.assign({count: 1}, attrs, {seed: ySeed});
let randomXs = random(startX, endX, xAttrs);
let randomYs = random(startY, endY, yAttrs);
return (xAttrs.count == 1 && yAttrs.count == 1) ? [randomXs, randomYs] : map((x,y) => [x,y], randomXs, randomYs);
};
const randomItem = (arr = [], attrs) => {
let indices = random(0, (arr.length - 1), merge(attrs, {asInt: true}), true);
return (isArr(indices)) ? map(x => arr[x], indices) : (arr[indices] ? arr[indices] : null);
};
/* HOFs */
const partial = (f,x) => (y) => f(x,y);
const identity = x => x;
const repeat = (obj, times) => new Array(times).fill(obj);
const repeatedly = (f,times,v) => map(() => f(v), tail(range(0, times)));
const constantly = (f,times,v) => reduce((i,n) => f(i), v, range(1,times));
const interpose = (l1, l2) => mapcat((x,y) => [x,y], l1,l2);
const grid = ({x = 0,y = 0, width, height}, hdiv, vdiv, hasEdge = false, {width: tileWidth = 0, height: tileHeight = 0} = {}) => {
let startX = x, endX = x + width;
let startY = y, endY = y + height;
let xs = steps(startX, endX, hdiv + 2);
let ys = steps(startY, endY, vdiv + 2);
if(!hasEdge) {
xs = xs.slice(1, xs.length - 1);
ys = ys.slice(1, ys.length - 1);
}
return mapcat(x => map(y => [x - tileWidth/2,y - tileHeight/2], ys), xs);
};
const reduce = (f, init, coll) => {
if(!coll) { coll = init.slice(1); init = init[0];}
for(let i = 0; i < coll.length; i++) init = f(init,coll[i]);
return init;
};
const makeIterable = (o) => (o && f.isObj(o)) ? Object.entries(o) : o;
const map = (f, coll, coll2, ...colls) => {
const DEBUG = true;
DEBUG && !isArr(coll) && console.warn("Please provide an array to map");
let res = [], count = null;
if(colls.length > 0) {
DEBUG && !isEvery(x => isArr(x), colls) && console.warn("Please provide arrays as input");
const bigColl = [coll,coll2].concat(colls);
console.log(transpose(bigColl));
return map(x => f.apply(null,x), transpose(bigColl));
} else {
DEBUG && !isArr(coll) && console.warn("Please provide an array to map along with first input");
count = coll2 ? Math.min(coll.length, coll2.length) : coll.length;
for(let i = 0; i < count; i++) {
(!coll2) ? res.push(f(coll[i])) : res.push(f(coll[i], coll2[i]));
}
}
return res;
};
const mapidx = (f,coll) => {
var res = [];
for(var i = 0; i < coll.length; i++) {
res.push(f(i,coll[i]));
}
return res;
}
const filter = (f, coll, coll2, ...colls) => {
let res = [], count = null;
if(colls.length > 0) {
const bigColl = [coll,coll2].concat(colls);
return filter(x => f.apply(null,x), transpose(bigColl));
} else {
count = coll2 ? Math.min(coll.length, coll2.length) : coll.length;
for(let i = 0; i < count; i++) {
if(!coll2) {
if(f(coll[i])) res.push(coll[i]);
} else {
if(f(coll[i], coll2[i]))
res.push([coll[i], coll2[i]]);
}
}
}
return res;
};
const mapcat = (f, ...colls) => reduce(concat, [], map(f,...colls));
const partition = (xs, n, step = 0) => {
n = Math.max(n,1);
step = Math.min(step, n - 1);
let nextItem = 0;
let result = [];
for(var i = 0; i < xs.length; i += n) {
i = Math.max(0, i - step);
const start = i;
const end = start + n;
result.push(xs.slice(start, end));
}
let remaining = xs.slice(i + n);
if(remaining.length > 0) result.push(remaining);
return result;
};
const rollover = (x, count = 0, asCopy) => {
let head = x.slice(0,count);
if(asCopy) {
return x.concat(head);
} else {
let tail = x.slice(count);
return tail.concat(head);
}
};
/* Range and Steps */
const range = (from, to, step) => {
step = Math.abs(step) || 1;
if(!to) { to = from; from = 0;}
const r = [];
const direction = Math.sign(to - from);
for(let i = from; (direction != 0) && (direction > 0 ? i <= to : i >= to); i += step * direction) r.push(i);
return r;
};
const steps = (from, to, count) => {
/* Resort to 1 in case (count - 1) is zero
Ensure division by zero is avoided */
const scalar = count - 1 || 1;
// Need to find a way to reduce the repetition of code for 2D and 1D
if(isArr(from) && isArr(to)) {
const dist = vSub(to, from);
const stepSize = vDiv(dist, scalar);
return map(step => vAdd(from, vMul(stepSize, step)), range(count).slice(0,-1));
};
const dist = to - from;
const stepSize = dist/scalar;
return map(step => from + (step * stepSize), range(count).slice(0,-1));
};
/* Object Ops */
const kvreduce = (f,init,o) => {
if(o) {
return Object.entries(o).reduce((acc, [k,v]) => f(acc,k,v), init);
} else {
o = init;
return Object.entries(o).reduce((acc, [k,v]) => f(acc,k,v), {});
}
}
const kvmap = (f,o) => kvreduce((acc,k,v) => merge(acc, f(k,v)), o);
const kvfilter = (f,o) => kvreduce((acc,k,v) => {
let result = f(k,v);
return result ? merge(acc, {[k]: v}) : acc;
}, o);
const arrTreeWalk = (fn, tree) => treeFold(tree, {node: n => n[0], children: ({subtree}) => tree.slice(1), folder: (n,c) => notEmpty(n) ? [n].concat(c) : [], processor: fn});
// Folder should take care of the cases when either node or children is null
// Walker could be used to take care of the case when children is null
const treeFold = (tree, params) => {
let {node: detectNode, children: detectChildren, walker, folder} = params;
if(isEmpty(tree)) return tree;
let pnode = null;
let node = tree;
if(detectNode) {
pnode = detectNode(tree);
node = pnode;
}
const children = detectChildren({pnode, subtree: tree});
const childNodes = walker ? walker(tree => treeFold(tree, params), node, children) : children.map(tree => treeFold(tree, params));
return folder(node, childNodes);
};
const time = (f) => {
let start = performance.now();
f();
let end = performance.now();
return (end - start).toPrecision(3) + " ms";
}
const mapKeys = (f,o) => kvreduce((acc,k,v) => merge(acc, {[f(k,v)]: v}), o);
const mapVals = (f,o) => kvreduce((acc,k,v) => merge(acc, {[k]: f(k,v)}), o);
/* Equality */
const objEq = (x,y) => {
let xks = Object.keys(x).sort();
let xvs = Object.values(x).sort();
let yks = Object.keys(y).sort();
let yvs = Object.values(y).sort();
let innerChecks = xvs.length == yvs.length && isEvery(eq, xvs, yvs);
let result = innerChecks && xks.length == yks.length && JSON.stringify(xks) === JSON.stringify(yks);
return result;
};
const eq = (x,y) => {
if(typeof x == "function" && typeof y == "function") {
return eq(x.toString(), y.toString());
} else if(typeof Set != "undefined" && x instanceof Set && y instanceof Set) {
return eq([...x].sort(), [...y].sort());
} else if(isObj(x) && isObj(y)) {
return objEq(x,y);
} else if(isArr(x) && isArr(y)) {
return x.length === y.length && isEvery(eq,x,y);
} else {
return x === y;
}
};
/* Diffs */
// [3,4], [3, 5] => 5
// ["input", {type: "text", class: "valid"}] -> ["input", {type: "text", class: "invalid"}]
// {class: "invalid"}
const diffVals = (x, y, {showEq = true} = {}) => {
if(eq(x,y)) {
return (showEq ? {"eq": x} : null);
} else {
let xSub = x != null ? {sub: x} : {};
let ySub = y != null ? {add: y} : {};
const result = merge({}, xSub, ySub);
return (isEmpty(result)) ? null : result;
}
}
const fillDelta = (arr1, arr2, filler = null) => {
if(arr1.length == arr2.length) {
return [arr1, arr2];
} else if(arr1.length > arr2.length) {
return [arr1, arr2.concat(repeat(filler, arr1.length - arr2.length))];
} else {
return [arr1.concat(repeat(filler, arr2.length - arr1.length)), arr2];
}
};
const normalizeArrs = (arr1 = [], arr2 = [], filler = null) => fillDelta(arr1, arr2, filler);
// TODO:
// Alternate idea is [arr1, arr2].map(fillTillLengthOfMax)
// But this seems a bit of a tradeoff of ease of expression with speed
// TO THINK:
// Should I use null or undefined?
const diffObjs = (obj1, obj2, {showEq} = {}) => {
return reduce((i,k) => {
let result = diff(obj1[k], obj2[k], {showEq});
if(isObj(result)) {
result = isAny(x => !isEmpty(x), Object.values(result)) ? result : null;
}
return result != null ? merge(i, {[k]: result}) : i;
}, {}, [...new Set(Object.keys(obj1).concat(Object.keys(obj2)))]);
};
const diffArrs = (arr1, arr2, {showEq} = {}) => map((x,y) => diff(x,y, {showEq}), ...normalizeArrs(arr1, arr2, null)).filter(x => x != null);
const diff = (state1, state2, {showEq} = {}) => {
if(state1 instanceof Array && state2 instanceof Array) {
return diffArrs(state1, state2, {showEq});
} else if(isObj(state1) && isObj(state2)) {
return diffObjs(state1, state2, {showEq});
} else {
return diffVals(state1, state2, {showEq});
}
};
if(typeof module != "undefined" && module.exports) {
module.exports = {merge, assoc, dissoc, update, renameKeys, transpose, repeat, range, steps, reduce, map, kvmap, kvfilter, mapKeys, mapVals, kvreduce, partition, rollover, grid, mapcat, objEq, eq, diffArrs, diffVals, diffObjs, diff, isArr, head, tail, isEmpty, normalizeArrs, isObj, partial, identity, find, random, randomVec, randomItem, vAdd, vSub, vMul, vDiv, vMag, vRot, vUnit, isAny, isEvery, notEmpty, time};
};
export {merge, assoc, dissoc, update, renameKeys, transpose, repeat, range, steps, reduce, map, kvmap, kvfilter, mapKeys, mapVals, kvreduce, partition, rollover, grid, mapcat, objEq, eq, diffArrs, diffVals, diffObjs, diff, isArr, head, tail, isEmpty, normalizeArrs, isObj, partial, identity, find, random, randomVec, randomItem, vAdd, vSub, vMul, vDiv, vMag, vRot, vUnit, isAny, isEvery, notEmpty, treeFold, time};