atomic-fns 0.2.2 → 0.2.3

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.
Files changed (64) hide show
  1. package/README.md +5 -3
  2. package/package.json +6 -7
  3. package/src/collections/index.d.ts +658 -0
  4. package/src/collections/index.js +1068 -0
  5. package/src/collections/index.ts +1162 -0
  6. package/src/datetime/index.d.ts +6 -0
  7. package/src/datetime/index.js +6 -0
  8. package/src/datetime/index.ts +7 -0
  9. package/src/{functools.d.ts → functools/index.d.ts} +8 -7
  10. package/src/functools/index.js +84 -0
  11. package/src/{functools.ts → functools/index.ts} +9 -7
  12. package/src/globals/index.d.ts +291 -0
  13. package/src/globals/index.js +391 -0
  14. package/src/globals/index.ts +456 -0
  15. package/src/index.d.ts +8 -7
  16. package/src/index.js +8 -7
  17. package/src/index.ts +8 -7
  18. package/src/itertools/index.d.ts +254 -0
  19. package/src/itertools/index.js +485 -0
  20. package/src/itertools/index.ts +511 -0
  21. package/src/math/index.d.ts +21 -0
  22. package/src/math/index.js +39 -0
  23. package/src/math/index.ts +44 -0
  24. package/src/{operators.d.ts → operators/index.d.ts} +8 -6
  25. package/src/operators/index.js +171 -0
  26. package/src/{operators.ts → operators/index.ts} +75 -30
  27. package/src/random/index.d.ts +42 -0
  28. package/src/random/index.js +65 -0
  29. package/src/random/index.ts +66 -0
  30. package/tests/collections.spec.ts +42 -25
  31. package/tests/globals.spec.ts +51 -47
  32. package/tests/itertools.spec.ts +190 -4
  33. package/tests/operators.spec.ts +1 -26
  34. package/tests/random.spec.ts +46 -0
  35. package/tsconfig.json +12 -4
  36. package/src/collections.d.ts +0 -228
  37. package/src/collections.js +0 -553
  38. package/src/collections.ts +0 -641
  39. package/src/datetime.d.ts +0 -5
  40. package/src/datetime.js +0 -5
  41. package/src/datetime.ts +0 -6
  42. package/src/functools.js +0 -78
  43. package/src/globals.d.ts +0 -179
  44. package/src/globals.js +0 -309
  45. package/src/globals.ts +0 -377
  46. package/src/itertools.d.ts +0 -20
  47. package/src/itertools.js +0 -98
  48. package/src/itertools.ts +0 -116
  49. package/src/math.d.ts +0 -16
  50. package/src/math.js +0 -70
  51. package/src/math.ts +0 -77
  52. package/src/objects.d.ts +0 -0
  53. package/src/objects.js +0 -1
  54. package/src/objects.ts +0 -0
  55. package/src/operators.js +0 -109
  56. package/src/random.d.ts +0 -22
  57. package/src/random.js +0 -48
  58. package/src/random.ts +0 -53
  59. package/src/strings.d.ts +0 -0
  60. package/src/strings.js +0 -1
  61. package/src/strings.ts +0 -0
  62. package/src/util.d.ts +0 -0
  63. package/src/util.js +0 -1
  64. package/src/util.ts +0 -0
@@ -0,0 +1,1068 @@
1
+ /**
2
+ * This module includes classes and functions to work with Container types.
3
+ *
4
+ * @module Collections
5
+ */
6
+ import { partial } from '../functools/index.js';
7
+ import { call, get, isArray, isArrayLike, isBool, isEmpty, isFunc, isIterable, isNull, isNumber, isObject, isString, isSymbol, keys, NotImplementedError, set } from '../globals/index.js';
8
+ import { enumerate } from '../itertools/index.js';
9
+ import { comp, eq, id } from '../operators/index.js';
10
+ /**
11
+ * A `Collection` is an iterable {@link Container} type.
12
+ * This is an abstract base class for user-defined collection types.
13
+ *
14
+ *
15
+ * @abstract
16
+ * @class Collection
17
+ * @implements {Container}
18
+ */
19
+ export class Collection {
20
+ /**
21
+ * Returns an iterator for the container items
22
+ * @return {Iterator}
23
+ */
24
+ [Symbol.iterator]() {
25
+ return this;
26
+ }
27
+ /**
28
+ * Implements the iterator protocol and returns the next item in the iterable.
29
+ */
30
+ next() { }
31
+ /**
32
+ * Adds a new item to the container.
33
+ * @param item - The item to add to the collection.
34
+ */
35
+ add(item) { }
36
+ /**
37
+ * Checks if item is present in the container.
38
+ * @param item - The item to search for in the collection.
39
+ * @returns `true` when the element is found, else `false`
40
+ */
41
+ contains(item) {
42
+ return false;
43
+ }
44
+ /**
45
+ * Returns the total number of elements in the container.
46
+ */
47
+ size() {
48
+ throw new NotImplementedError();
49
+ }
50
+ /**
51
+ * Remove the first item from the container where `item == x`
52
+ * @returns `true` when the element is found and removed, else `false`
53
+ */
54
+ remove(x) {
55
+ return false;
56
+ }
57
+ /**
58
+ * Retrieve and remove the item at index `i`.
59
+ * @returns the item or undefined if not found.
60
+ */
61
+ pop(i) { }
62
+ /**
63
+ * Remove all items from the container
64
+ */
65
+ clear() { }
66
+ }
67
+ /**
68
+ * A sequence is an iterable {@link Collection} type with efficient index-based access.
69
+ * @abstract
70
+ * @class Sequence
71
+ * @extends {Collection}
72
+ * @template T
73
+ */
74
+ export class Sequence extends Collection {
75
+ /**
76
+ * Return the item at the given key or index
77
+ * @param {*} key
78
+ * @memberof Sequence
79
+ */
80
+ get(key) {
81
+ throw new NotImplementedError();
82
+ }
83
+ /**
84
+ * Set a new value at the given key or index
85
+ *
86
+ * @param {*} key
87
+ * @param {T} val
88
+ * @memberof Sequence
89
+ */
90
+ set(key, val) {
91
+ throw new NotImplementedError();
92
+ }
93
+ /**
94
+ * Deletes the given key or index, and its value.
95
+ * Raises ValueError if not key is found.
96
+ *
97
+ * @param {*} key
98
+ * @memberof Sequence
99
+ */
100
+ delete(key) {
101
+ throw new NotImplementedError();
102
+ }
103
+ /**
104
+ * Adds a new item to the end of the sequence.
105
+ *
106
+ * @param {T} x
107
+ * @memberof Sequence
108
+ */
109
+ append(x) { }
110
+ /**
111
+ * Append all the items to the sequence.
112
+ *
113
+ * @param {Iterable<T>} iter
114
+ * @memberof Sequence
115
+ */
116
+ extend(iter) { }
117
+ /**
118
+ * Return the index of x in the sequence, or undefined if not found.
119
+ *
120
+ * @param {T} item
121
+ * @return {(number | undefined)}
122
+ * @memberof Sequence
123
+ */
124
+ indexOf(item) {
125
+ throw new NotImplementedError();
126
+ }
127
+ size() {
128
+ return 0;
129
+ }
130
+ reversed() {
131
+ throw new NotImplementedError();
132
+ }
133
+ }
134
+ /**
135
+ * Returns a new immutable Set object with elements from `iterable`. Its contents cannot be altered after it's created.
136
+ *
137
+ *
138
+ * @class FrozenSet
139
+ * @extends {Set<T>}
140
+ * @template T
141
+ */
142
+ export class FrozenSet extends Set {
143
+ constructor(iterable) {
144
+ super(iterable);
145
+ return this.freeze();
146
+ }
147
+ /** @private */
148
+ add() {
149
+ throw TypeError('FrozenSet cannot be modified.');
150
+ return this; // eslint-disable-line
151
+ }
152
+ /** @private */
153
+ delete() {
154
+ throw TypeError('FrozenSet cannot be modified.');
155
+ return false; // eslint-disable-line
156
+ }
157
+ /** @private */
158
+ clear() {
159
+ throw TypeError('FrozenSet cannot be modified.');
160
+ return this; // eslint-disable-line
161
+ }
162
+ /** @private */
163
+ freeze() {
164
+ return Object.freeze(this);
165
+ }
166
+ }
167
+ export function compact(arr) {
168
+ if (arr == null)
169
+ return;
170
+ if (Array.isArray(arr))
171
+ return arr.filter((x) => !isEmpty(x));
172
+ const result = {};
173
+ for (const key of Object.keys(arr)) {
174
+ if (!isEmpty(arr[key])) {
175
+ result[key] = arr[key];
176
+ }
177
+ }
178
+ return result;
179
+ }
180
+ export function count(iterable, func) {
181
+ const counters = {};
182
+ forEach(iterable, (value, key) => {
183
+ const result = func(value, key);
184
+ counters[result] = get(result, counters, 0) + 1;
185
+ });
186
+ return counters;
187
+ }
188
+ /**
189
+ * Creates a function that can be used to create named tuple-like objects.
190
+ * @example
191
+ ```js
192
+ * let Point = namedtuple('x', 'y', 'z')
193
+ * let userObj = User(0, 0, 0)
194
+ * // => {x: 0, y: 0, z: 0}
195
+ ```
196
+ * @param fields - A list of field names
197
+ * @returns A function that can be called with the field values
198
+ */
199
+ export function namedtuple(...fields) {
200
+ return (...args) => fields.reduce((prev, f, i) => set(f, prev, args[i], false, true), {});
201
+ }
202
+ /**
203
+ * Iterates over elements of collection, returning an array of all elements where predicate returns truthy value.
204
+ *
205
+ * The predicate is invoked with three arguments: `(value, index|key, arr)`.
206
+ *
207
+ * @example
208
+ ```js
209
+ * let users = [
210
+ { 'user': 'barney', 'age': 36, 'active': true },
211
+ { 'user': 'fred', 'age': 40, 'active': false }
212
+ ]
213
+
214
+ filter(users, o => !o.active)
215
+ // => objects for ['fred']
216
+
217
+ // The shape iteratee shorthand.
218
+ filter(users, { age: 36, active: true })
219
+ // => objects for ['barney']
220
+
221
+ // The property iteratee shorthand.
222
+ filter(users, 'active')
223
+ // => objects for ['barney']
224
+ ```
225
+ * @param {Array} arr The collection to iterate over
226
+ * @param {Function} fn The predicate function invoked for each item
227
+ * @returns {Array} The new filtered array
228
+ */
229
+ export function filter(arr, fn = isNull) {
230
+ if (Array.isArray(arr)) {
231
+ if (isFunc(fn))
232
+ return arr.filter(fn);
233
+ if (isNumber(fn) || isString(fn) || isSymbol(fn))
234
+ return arr.filter((x) => get(fn, x));
235
+ if (isObject(fn))
236
+ return arr.filter(matches(fn));
237
+ }
238
+ }
239
+ /**
240
+ * Iterates over elements of collection, returning the first element where predicate returns truthy value. The predicate is invoked with three arguments: `(value, index|key, collection)`.
241
+ * @example
242
+ ```js
243
+ let users = [
244
+ { 'user': 'barney', 'age': 36, 'active': true },
245
+ { 'user': 'fred', 'age': 40, 'active': false },
246
+ { 'user': 'pebbles', 'age': 1, 'active': true }
247
+ ]
248
+
249
+ find(users, (o) => o.age < 40)
250
+ // => object for 'barney'
251
+
252
+ // The shape iteratee shorthand.
253
+ find(users, { 'age': 1, 'active': true })
254
+ // => object for 'pebbles'
255
+
256
+ // The `property` iteratee shorthand.
257
+ find(users, 'active')
258
+ // => object for 'barney'
259
+ ```
260
+ * @param {Array} arr The collection to iterate over.
261
+ * @param {Function} fn The function invoked per iteration.
262
+ * @returns {*} The matched element, else `undefined`.
263
+ * @see {@link findRight}
264
+ */
265
+ export function find(arr, fn) {
266
+ if (Array.isArray(arr)) {
267
+ if (isFunc(fn))
268
+ return arr.find(fn);
269
+ if (isNumber(fn) || isString(fn) || isSymbol(fn))
270
+ return arr.find((x) => x?.[fn]);
271
+ if (isObject(fn))
272
+ return arr.find(matches(fn));
273
+ }
274
+ }
275
+ /**
276
+ * This method is like {@link find} except that it iterates from right to left.
277
+ * @example
278
+ ```js
279
+ findRight([1, 2, 3, 4], (n) => n % 2 === 1)
280
+ // => 3
281
+ ```
282
+ * @param {Array} arr The collection to iterate over.
283
+ * @param {Function} fn The function invoked per iteration.
284
+ * @returns {*} The matched element, else `undefined`.
285
+ * @see {@link find}
286
+ */
287
+ export function findRight(arr, fn) {
288
+ if (Array.isArray(arr)) {
289
+ for (let i = arr.length - 1; i >= 0; i--) {
290
+ const x = arr[i];
291
+ if (typeof fn === 'function') {
292
+ if (fn(x))
293
+ return x;
294
+ }
295
+ else if (typeof fn === 'string') {
296
+ if (x?.[fn])
297
+ return x;
298
+ }
299
+ else if (isObject(fn)) {
300
+ if (matches(fn)(x))
301
+ return x;
302
+ }
303
+ }
304
+ }
305
+ }
306
+ /**
307
+ * Creates a function that performs a partial deep comparison between a given object and `shape`, returning `true` if the given object has equivalent property values, else `false`.
308
+ * @example
309
+ ```js
310
+ let objects = [
311
+ { a: 1, b: 2, c: 3 },
312
+ { a: 4, b: 5, c: 6 }
313
+ ]
314
+
315
+ filter(objects, matches({ a: 4, c: 6 }))
316
+ // => [{ a: 4, b: 5, c: 6 }]
317
+ ```
318
+ * @param shape
319
+ * @returns
320
+ */
321
+ export const matches = (shape) => (obj) => {
322
+ if (!shape || !obj)
323
+ return false;
324
+ for (const key in shape) {
325
+ if (obj[key] !== shape[key])
326
+ return false;
327
+ }
328
+ return true;
329
+ };
330
+ export function forEach(collection, fn) {
331
+ if (Array.isArray(collection)) {
332
+ for (let i = 0; i < collection.length; i++) {
333
+ const res = fn(collection[i], i, collection);
334
+ if (res === false)
335
+ return collection;
336
+ }
337
+ }
338
+ else if (isIterable(collection)) {
339
+ for (const [index, value] of enumerate(collection)) {
340
+ const res = fn(value, index, collection);
341
+ if (res === false)
342
+ return collection;
343
+ }
344
+ }
345
+ else {
346
+ for (const key of keys(collection)) {
347
+ const res = fn(collection[key], key, collection);
348
+ if (res === false)
349
+ return collection;
350
+ }
351
+ }
352
+ }
353
+ /**
354
+ * This method is like {@link forEach} except that it iterates over the collection from right to left.
355
+
356
+ * @example
357
+ ```js
358
+ forEachRight([1, 2], (value) => {
359
+ console.log(value)
360
+ })
361
+ // => Logs `2` then `1`.
362
+ ```
363
+ * @param {Array|Object} collection The collection to iterate over.
364
+ * @param {Iteratee} fn The function invoked per iteration.
365
+ * @returns {*} Returns `collection`.
366
+ * @see {@link forEach}
367
+ * @see {@link filter}
368
+ * @see {@link map}
369
+ */
370
+ export function forEachRight(collection, fn) {
371
+ if (Array.isArray(collection)) {
372
+ for (let i = collection.length - 1; i >= 0; i--) {
373
+ const value = collection[i];
374
+ const res = fn(value, i, collection);
375
+ if (res === false)
376
+ return collection;
377
+ }
378
+ }
379
+ else if (isObject(collection)) {
380
+ const keys = Object.keys(collection);
381
+ for (let i = keys.length - 1; i >= 0; i--) {
382
+ const key = keys[i];
383
+ const value = collection[key];
384
+ const res = fn(value, i, collection);
385
+ if (res === false)
386
+ return collection;
387
+ }
388
+ }
389
+ return collection;
390
+ }
391
+ /**
392
+ * Flattens an array or object. Arrays will be flattened recursively up to `depth` times. Objects will be flattened recursively.
393
+ * @example
394
+ ```js
395
+ flatten([1, [2, [3, [4]], 5]])
396
+ // => [1, 2, [3, [4]], 5]
397
+
398
+ flatten({
399
+ dates: {
400
+ expiry_date: '30 sep 2018',
401
+ available: '30 sep 2017',
402
+ min_contract_period: [
403
+ {
404
+ id: 1,
405
+ name: '1 month'
406
+ }
407
+ ]
408
+ },
409
+ price: {
410
+ currency: 'RM',
411
+ value: 1500
412
+ }
413
+ })
414
+ // => {
415
+ 'dates.expiry_date': '30 sep 2018',
416
+ 'dates.available': '30 sep 2017',
417
+ 'dates.min_contract_period[0].id': 1,
418
+ 'dates.min_contract_period[0].name': '1 month',
419
+ 'price.currency': 'RM',
420
+ 'price.value': 1500
421
+ }
422
+ ```
423
+ * @param {Array|Object} arr The array or object to flatten.
424
+ * @param {number} [depth=1] The max recursion depth.
425
+ * @returns {*} The new flattened array or object.
426
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat Array.flat()}
427
+ */
428
+ export function flatten(arr, depth = 1) {
429
+ if (!depth)
430
+ return arr;
431
+ if (Array.isArray(arr))
432
+ return flattenArray(arr, depth, []);
433
+ if (isObject(arr))
434
+ return flattenObj(arr);
435
+ return arr;
436
+ }
437
+ function flattenArray(arr, depth = 1, result = []) {
438
+ for (const value of arr) {
439
+ if (depth && Array.isArray(value)) {
440
+ flattenArray(value, typeof depth === 'number' ? depth - 1 : depth, result);
441
+ }
442
+ else {
443
+ result.push(value);
444
+ }
445
+ }
446
+ return result;
447
+ }
448
+ function flattenObj(obj, prefix = '', result = {}, keepNull = false) {
449
+ if (isString(obj) || isNumber(obj) || isBool(obj) || (keepNull && isNull(obj))) {
450
+ result[prefix] = obj;
451
+ return result;
452
+ }
453
+ if (isArray(obj) || isObject(obj)) {
454
+ for (const i of Object.keys(obj)) {
455
+ let pref = prefix;
456
+ if (isArray(obj)) {
457
+ pref = `${pref}[${i}]`;
458
+ }
459
+ else {
460
+ if (prefix) {
461
+ pref = `${prefix}.${i}`;
462
+ }
463
+ else {
464
+ pref = i;
465
+ }
466
+ }
467
+ flattenObj(obj[i], pref, result, keepNull);
468
+ }
469
+ return result;
470
+ }
471
+ return result;
472
+ }
473
+ /**
474
+ * Creates an array of values by running each element in collection thru iteratee. The iteratee is invoked with three arguments: `(value, index|key, collection)`.
475
+ * @example
476
+ ```js
477
+ function square(n) {
478
+ return n * n
479
+ }
480
+
481
+ map([4, 8], square)
482
+ // => [16, 64]
483
+
484
+ map({ a: 4, b: 8 }, square)
485
+ // => [16, 64] (iteration order is not guaranteed)
486
+
487
+ let users = [
488
+ { user: 'barney' },
489
+ { user: 'fred' }
490
+ ]
491
+
492
+ // The `property` iteratee shorthand.
493
+ map(users, 'user')
494
+ // => ['barney', 'fred']
495
+ ```
496
+ * @param {Array|Object} arr The collection to iterate over.
497
+ * @param {Iteratee|PropertyKey} fn The function invoked per iteration.
498
+ * @returns Returns the new mapped array.
499
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map Array.map()}
500
+ */
501
+ export function map(arr, fn) {
502
+ if (Array.isArray(arr)) {
503
+ return arr.map((x, i) => {
504
+ if (typeof fn === 'function')
505
+ return fn(x, i, arr);
506
+ return x?.[fn];
507
+ });
508
+ }
509
+ if (isObject(arr)) {
510
+ return Object.keys(arr).map((key) => {
511
+ if (typeof fn === 'function')
512
+ return fn(arr[key], key, arr);
513
+ return get(fn, arr[key]);
514
+ });
515
+ }
516
+ }
517
+ /**
518
+ * Creates an object composed of the picked object properties.
519
+ * @param {Object} obj The source object.
520
+ * @param {Iteratee|PropertyKey[]} paths The properties to pick. If `paths` is a function, it will be invoked per property with two values `(value, key)`.
521
+ * @returns A new object with the properties.
522
+ * @example
523
+ ```js
524
+ let object = { a: 1, b: '2', c: 3 }
525
+
526
+ pick(object, ['a', 'c'])
527
+ // => { a: 1, c: 3 }
528
+
529
+ pick(object, (x) => isNumber(x))
530
+ // => { a: 1, c: 3 }
531
+ ```
532
+ *
533
+ * @see {@link omit}
534
+ */
535
+ export function pick(obj, paths) {
536
+ if (!obj)
537
+ return {};
538
+ const result = {};
539
+ if (typeof paths === 'function') {
540
+ for (const key of Object.keys(obj)) {
541
+ if (paths(obj[key], key)) {
542
+ result[key] = obj[key];
543
+ }
544
+ }
545
+ return result;
546
+ }
547
+ for (const key of paths) {
548
+ result[key] = get(key, obj);
549
+ }
550
+ return result;
551
+ }
552
+ /**
553
+ * The opposite of {@link pick} - this method creates an object composed of the own and inherited enumerable property paths of `object` that are not omitted.
554
+ * @example
555
+ ```js
556
+ let object = { 'a': 1, 'b': '2', 'c': 3 }
557
+
558
+ omit(object, ['a', 'c'])
559
+ // => { 'b': '2' }
560
+
561
+ omit(object, (x) => isNumber(x))
562
+ // => { 'b': '2' }
563
+ ```
564
+ * @param {Object} obj The source object.
565
+ * @param {Iteratee|PropertyKey[]} paths The property paths to omit.
566
+ * @returns {Object} Returns the new object.
567
+ * @see {@link pick}
568
+ */
569
+ export function omit(obj, paths) {
570
+ if (!obj)
571
+ return {};
572
+ const result = {};
573
+ if (typeof paths === 'function') {
574
+ for (const key of Object.keys(obj)) {
575
+ if (!paths(obj[key], key)) {
576
+ result[key] = obj[key];
577
+ }
578
+ }
579
+ return result;
580
+ }
581
+ Object.assign(result, obj);
582
+ for (const key of paths) {
583
+ delete result[key];
584
+ }
585
+ return result;
586
+ }
587
+ /**
588
+ * This method is like {@link find} except that it returns the index of the first element `predicate` returns truthy for instead of the element itself.
589
+ * @param {Array} obj The array to inspect.
590
+ * @param {string|Object|Iteratee} fn The predicate function
591
+ * @param {number} [start=0] The index to search from.
592
+ * @returns {number} The index of the found value, else -1
593
+ * @example
594
+ ```js
595
+ let users = [
596
+ { 'user': 'barney', 'active': false },
597
+ { 'user': 'fred', 'active': false },
598
+ { 'user': 'pebbles', 'active': true }
599
+ ]
600
+
601
+ index(users, (o) => o.user == 'barney')
602
+ // => 0
603
+
604
+ // The `shape` iteratee shorthand.
605
+ index(users, { 'user': 'fred', 'active': false })
606
+ // => 1
607
+
608
+ // The `property` iteratee shorthand.
609
+ index(users, 'active')
610
+ // => 2
611
+ ```
612
+ * @see {@link indexOf}
613
+ * @see {@link lastIndex}
614
+ *
615
+ */
616
+ export function index(obj, fn, start = 0) {
617
+ if (obj == null)
618
+ return;
619
+ const length = obj.length;
620
+ if (length && start < 0) {
621
+ start = Math.max(start + length, 0);
622
+ }
623
+ if (!length || start >= length)
624
+ return -1;
625
+ if (isObject(fn)) {
626
+ fn = matches(fn);
627
+ }
628
+ for (; start < length; start++) {
629
+ if (typeof fn === 'function') {
630
+ if (fn(obj[start], start, obj))
631
+ return start;
632
+ }
633
+ else {
634
+ if (obj[start]?.[fn])
635
+ return start;
636
+ }
637
+ }
638
+ return -1;
639
+ }
640
+ /**
641
+ * This method is like {@link index} except that it searches for a given value directly, instead of using a predicate function.
642
+ * @param {Array} obj The array to inspect.
643
+ * @param {*} value The value to find
644
+ * @param {number} [start=0] The index to search from.
645
+ * @returns {number} The index of the found value, else -1
646
+ * @example
647
+ ```js
648
+ indexOf([1, 2, 1, 2], 2)
649
+ // => 1
650
+
651
+ // Search from a `start` index.
652
+ indexOf([1, 2, 1, 2], 2, 2)
653
+ // => 3
654
+ ```
655
+ * @see {@link index}
656
+ * @see {@link lastIndexOf}
657
+ */
658
+ export function indexOf(obj, value, start = 0) {
659
+ if (obj == null)
660
+ return;
661
+ const op = call(obj, 'indexOf', value, start);
662
+ if (op != null)
663
+ return op;
664
+ const length = obj.length;
665
+ if (length && start < 0) {
666
+ start = Math.max(start + length, 0);
667
+ }
668
+ if (!length || start >= length)
669
+ return -1;
670
+ for (; start < length; start++) {
671
+ if (eq(value, obj[start]))
672
+ return start;
673
+ }
674
+ return -1;
675
+ }
676
+ /**
677
+ * This method is like {@link index} except that it iterates the collection from right to left.
678
+ * @param {Array} obj The array to inspect.
679
+ * @param {string|Iteratee|Object} fn The function invoked per iteration.
680
+ * @param {number} [start] The index to search from.
681
+ * @returns {number} The index of the found value, else -1
682
+ * @example
683
+ ```js
684
+ let users = [
685
+ { 'user': 'barney', 'active': true },
686
+ { 'user': 'fred', 'active': false },
687
+ { 'user': 'pebbles', 'active': false }
688
+ ]
689
+
690
+ findLastIndex(users, (o) => o.user == 'pebbles')
691
+ // => 2
692
+
693
+ // The `shape` iteratee shorthand.
694
+ findLastIndex(users, { 'user': 'barney', 'active': true })
695
+ // => 0
696
+
697
+ // The `property` iteratee shorthand.
698
+ findLastIndex(users, 'active')
699
+ // => 0
700
+ ```
701
+ * @see {@link index}
702
+ * @see {@link lastIndexOf}
703
+ */
704
+ export function lastIndex(obj, fn, start) {
705
+ if (obj == null)
706
+ return;
707
+ const length = obj.length;
708
+ if (start == null)
709
+ start = length - 1;
710
+ if (!length || start < 0)
711
+ return -1;
712
+ if (isObject(fn)) {
713
+ fn = matches(fn);
714
+ }
715
+ for (; start >= 0; start--) {
716
+ if (typeof fn === 'function') {
717
+ if (fn(obj[start]))
718
+ return start;
719
+ }
720
+ else {
721
+ if (obj[start]?.[fn])
722
+ return start;
723
+ }
724
+ }
725
+ return -1;
726
+ }
727
+ /**
728
+ * This method is like {@link indexOf} except that it iterates the collection from right to left.
729
+ * @param {Array} obj The array to inspect.
730
+ * @param {*} value The value to find
731
+ * @param {number} [start] The index to search from.
732
+ * @returns {number} The index of the found value, else -1
733
+ * @example
734
+ ```js
735
+ lastIndexOf([1, 2, 1, 2], 2)
736
+ // => 3
737
+
738
+ // Search from the `fromIndex`.
739
+ lastIndexOf([1, 2, 1, 2], 2, 2)
740
+ // => 1
741
+ ```
742
+ * @see {@link lastIndex}
743
+ * @see {@link indexOf}
744
+ */
745
+ export function lastIndexOf(obj, value, start) {
746
+ if (obj == null)
747
+ return;
748
+ const op = call(obj, 'lastIndexOf', value, start);
749
+ if (op != null)
750
+ return op;
751
+ const length = obj.length;
752
+ if (start == null)
753
+ start = length - 1;
754
+ if (!length || start < 0)
755
+ return -1;
756
+ for (; start >= 0; start--) {
757
+ if (eq(value, obj[start]))
758
+ return start;
759
+ }
760
+ return -1;
761
+ }
762
+ /**
763
+ * Creates a shallow clone of `value`. If `deep` is `true` it will clone it recursively.
764
+ * @param {*} value
765
+ * @param {boolean} [deep=false]
766
+ * @return The clone value
767
+ * @see {@link cloneArray}
768
+ * @see {@link cloneTypedArray}
769
+ */
770
+ export function clone(value, deep = false) {
771
+ if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) {
772
+ return cloneTypedArray(value, deep);
773
+ }
774
+ if (isArray(value) || isArrayLike(value)) {
775
+ return cloneArray(value, deep);
776
+ }
777
+ if (isObject(value)) {
778
+ if (isFunc(value.clone)) {
779
+ return value.clone();
780
+ }
781
+ const copy = {};
782
+ for (const key in value) {
783
+ if (deep) {
784
+ copy[key] = clone(value[key], deep);
785
+ }
786
+ else {
787
+ copy[key] = value[key];
788
+ }
789
+ }
790
+ return copy;
791
+ }
792
+ return value;
793
+ }
794
+ /**
795
+ * Clones an array. If `deep` is `false` (default) the clone will be shallow. Otherwise {@link https://developer.mozilla.org/en-US/docs/Web/API/structuredClone structuredClone} is used.
796
+ * @param arr The array to clone
797
+ * @param [deep=false] Creates a deep clone using `structuredClone` if true.
798
+ * @returns The new array
799
+ * @see {@link clone}
800
+ */
801
+ export function cloneArray(arr, deep = false) {
802
+ if (!deep)
803
+ return Array.from(arr);
804
+ return structuredClone(arr);
805
+ }
806
+ /**
807
+ * Clones a typed array. If `deep` is `false` (default) the clone will be shallow. Otherwise {@link https://developer.mozilla.org/en-US/docs/Web/API/structuredClone structuredClone} is used.
808
+ * @param arr The array to clone
809
+ * @param [deep=false] Creates a deep clone using `structuredClone` if true.
810
+ * @returns The new array
811
+ * @see {@link clone}
812
+ */
813
+ export function cloneTypedArray(typedArray, isDeep) {
814
+ const buffer = isDeep ? structuredClone(typedArray) : typedArray.buffer;
815
+ return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
816
+ }
817
+ /**
818
+ * Creates a duplicate-free version of an array, using a `Set` for equality comparisons, in which only the first occurrence of each element is kept. The order of result values is not guaranteed.
819
+ * @param arr The array containing duplicated elements
820
+ * @param fn The iteratee invoked per element.
821
+ * @returns Returns the new duplicate free array.
822
+ * @example
823
+ ```js
824
+ uniq([2, 1, 2])
825
+ // => [2, 1]
826
+
827
+ uniq([2.1, 1.2, 2.3], Math.floor)
828
+ // => [2.1, 1.2]
829
+ ```
830
+ *
831
+ * @see {@link sortedUniq}
832
+ */
833
+ export function uniq(arr, fn = id) {
834
+ const keys = new Set();
835
+ const mapper = typeof fn === 'function' ? fn : (x) => x?.[fn];
836
+ for (const x of arr) {
837
+ keys.add(mapper(x));
838
+ }
839
+ return Array.from(keys.values());
840
+ }
841
+ /**
842
+ * This method is like {@link uniq} except that it sorts the results in ascending order
843
+ * @param arr The array containing duplicated elements
844
+ * @param fn The iteratee invoked per element.
845
+ * @returns Returns the new duplicate free array
846
+ * @example
847
+ ```js
848
+ uniq([2, 1, 2])
849
+ // => [1, 2]
850
+ ```
851
+ * @see {@link uniq}
852
+ */
853
+ export function sortedUniq(arr, fn = id) {
854
+ const values = uniq(arr, fn);
855
+ values.sort(comp);
856
+ return values;
857
+ }
858
+ function baseMergeDeep(obj, source, key, stack) {
859
+ const objValue = obj[key];
860
+ const srcValue = source[key];
861
+ const stacked = stack.get(srcValue);
862
+ if (stacked && (objValue !== stacked || !(key in obj))) {
863
+ obj[key] = stacked;
864
+ return;
865
+ }
866
+ let newValue;
867
+ let isCommon = newValue === undefined;
868
+ const isArray = Array.isArray(srcValue);
869
+ const isTyped = ArrayBuffer.isView(srcValue);
870
+ if (isArray || isTyped) {
871
+ if (Array.isArray(objValue)) {
872
+ newValue = objValue;
873
+ }
874
+ else if (isArrayLike(objValue)) {
875
+ newValue = Array.from(objValue);
876
+ }
877
+ else if (isTyped) {
878
+ isCommon = false;
879
+ newValue = cloneTypedArray(srcValue, true);
880
+ }
881
+ else {
882
+ newValue = [];
883
+ }
884
+ }
885
+ else if (isObject(srcValue)) {
886
+ newValue = objValue;
887
+ if (!isObject(objValue)) {
888
+ newValue = srcValue;
889
+ }
890
+ }
891
+ else {
892
+ isCommon = false;
893
+ }
894
+ if (isCommon) {
895
+ stack.set(srcValue, newValue);
896
+ baseMerge(newValue, srcValue, stack);
897
+ stack.delete(srcValue);
898
+ }
899
+ obj[key] = newValue;
900
+ }
901
+ function baseMerge(obj, source, stack) {
902
+ if (obj === source)
903
+ return obj;
904
+ for (const key of Object.keys(source)) {
905
+ const srcValue = source[key];
906
+ const objValue = obj[key];
907
+ if (typeof srcValue === 'object' && srcValue !== null) {
908
+ baseMergeDeep(obj, source, key, stack || new WeakMap());
909
+ }
910
+ else {
911
+ if (objValue !== srcValue) {
912
+ obj[key] = srcValue;
913
+ }
914
+ }
915
+ }
916
+ }
917
+ /**
918
+ * Recursively merges own and inherited enumerable string keyed properties of source objects into the destination object. Source properties that resolve to `undefined` are skipped if a destination value exists. Array and plain object properties are merged recursively. Other objects and value types are overridden by assignment. Source objects are applied from left to right. Subsequent sources overwrite property assignments of previous sources.
919
+ *
920
+ * Note: this method mutates `object`
921
+ *
922
+ *
923
+ * @param {Object} object The destination object.
924
+ * @param {...Object} sources The source objects.
925
+ * @returns Returns `object`.
926
+ *
927
+ * @example
928
+ ```js
929
+ let object = {
930
+ 'a': [{ 'b': 2 }, { 'd': 4 }]
931
+ }
932
+
933
+ let other = {
934
+ 'a': [{ 'c': 3 }, { 'e': 5 }]
935
+ }
936
+
937
+ merge(object, other)
938
+ // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
939
+ ```
940
+ */
941
+ export function merge(object, ...sources) {
942
+ for (const source of sources) {
943
+ baseMerge(object, source);
944
+ }
945
+ return object;
946
+ }
947
+ /**
948
+ * Returns a generator of array values not included in the other given arrays using a `Set` for equality comparisons. The order and references of result values are not guaranteed.
949
+ * @param args The initial arrays
950
+ * @example
951
+ ```js
952
+ [...difference([2, 1], [2, 3])]
953
+ // => [1]
954
+ ```
955
+ * @see {@link union}
956
+ * @see {@link intersection}
957
+ */
958
+ export function* difference(...args) {
959
+ const sets = args.map((arr) => new Set(arr));
960
+ const setA = sets[0];
961
+ for (let i = 1; i < sets.length; i++) {
962
+ for (const x of sets[i].values()) {
963
+ if (!setA.delete(x))
964
+ setA.add(x);
965
+ }
966
+ }
967
+ for (const x of setA.values()) {
968
+ yield x;
969
+ }
970
+ }
971
+ /**
972
+ * Creates a generator of unique values that are included in all given arrays.
973
+ * @param args The arrays to inspect
974
+ * @example
975
+ ```js
976
+ [...intersection([2, 1], [2, 3])]
977
+ // => [2]
978
+ ```
979
+ * @see {@link difference}
980
+ * @see {@link union}
981
+ */
982
+ export function* intersection(...args) {
983
+ const sets = args.map((arr) => new Set(arr));
984
+ // build a counter map to find items in all
985
+ const results = new Map();
986
+ const total = sets.length;
987
+ for (let i = 0; i < total; i++) {
988
+ for (const x of sets[i].values()) {
989
+ const count = results.get(x) || 0;
990
+ results.set(x, count + 1);
991
+ }
992
+ }
993
+ for (const [key, value] of results.entries()) {
994
+ if (value === total)
995
+ yield key;
996
+ }
997
+ }
998
+ /**
999
+ * Creates a generator of unique values from all given arrays using `Set` for equality comparisons.
1000
+ * @param args The arrays to perform union on.
1001
+ * @example
1002
+ ```js
1003
+ [...union([2], [1, 2])]
1004
+ // => [2, 1]
1005
+ ```
1006
+ * @see {@link difference}
1007
+ * @see {@link intersection}
1008
+ */
1009
+ export function* union(...args) {
1010
+ const results = new Set();
1011
+ for (const arr of args) {
1012
+ for (const item of arr) {
1013
+ results.add(item);
1014
+ }
1015
+ }
1016
+ for (const item of results.values()) {
1017
+ yield item;
1018
+ }
1019
+ }
1020
+ /**
1021
+ * Creates an object composed of keys generated from the results of running each element of `arr` thru `func`. The order of grouped values is determined by the order they occur in `arr`. The corresponding value of each key is an array of elements responsible for generating the key.
1022
+ *
1023
+ * @param arr The collection to iterate over.
1024
+ * @param [func=id] The iteratee to transform keys.
1025
+ * @returns Returns the composed aggregate object.
1026
+ *
1027
+ * @example
1028
+ ```js
1029
+ groupBy([6.1, 4.2, 6.3], Math.floor)
1030
+ // => { '4': [4.2], '6': [6.1, 6.3] }
1031
+
1032
+ // The `property` iteratee shorthand.
1033
+ groupBy(['one', 'two', 'three'], 'length')
1034
+ // => { '3': ['one', 'two'], '5': ['three'] }
1035
+ ```
1036
+ */
1037
+ export function groupBy(arr, func = id) {
1038
+ const results = {};
1039
+ const useKey = typeof func === 'function' ? func : partial(get, func);
1040
+ forEach(arr, (value) => {
1041
+ const groupKey = useKey(value);
1042
+ const values = results[groupKey] || [];
1043
+ values.push(value);
1044
+ results[groupKey] = values;
1045
+ });
1046
+ return results;
1047
+ }
1048
+ /**
1049
+ * Removes all elements from array that `func` returns truthy for and returns an array of the removed elements.
1050
+ * @param arr The array to remove from.
1051
+ * @param func The function invoked per iteration or value(s) or value to remove.
1052
+ * @returns
1053
+ */
1054
+ export function remove(arr, func) {
1055
+ return arr.filter((x, i) => {
1056
+ if (isArray(func))
1057
+ return !func.includes(x);
1058
+ else if (isFunc(func))
1059
+ return !func(x, i, arr);
1060
+ return x !== func;
1061
+ });
1062
+ }
1063
+ // TODO: binary search utils
1064
+ // TODO: heap/heapify
1065
+ // TODO: deque
1066
+ // TODO: Counter
1067
+ // TODO: Skip list
1068
+ // TODO: BST (BTree)