atomic-fns 0.2.0 → 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/.esdoc.json +19 -1
  2. package/.eslintrc.json +1 -0
  3. package/README.md +8 -9
  4. package/package.json +9 -9
  5. package/src/collections/index.d.ts +658 -0
  6. package/src/collections/index.js +1068 -0
  7. package/src/collections/index.ts +1162 -0
  8. package/src/datetime/index.d.ts +6 -0
  9. package/src/datetime/index.js +6 -0
  10. package/src/datetime/index.ts +7 -0
  11. package/src/{functools.d.ts → functools/index.d.ts} +10 -5
  12. package/src/{functools.js → functools/index.js} +9 -4
  13. package/src/{functools.ts → functools/index.ts} +11 -5
  14. package/src/globals/index.d.ts +291 -0
  15. package/src/globals/index.js +391 -0
  16. package/src/globals/index.ts +456 -0
  17. package/src/index.d.ts +8 -7
  18. package/src/index.js +8 -7
  19. package/src/index.ts +8 -7
  20. package/src/itertools/index.d.ts +254 -0
  21. package/src/itertools/index.js +485 -0
  22. package/src/itertools/index.ts +511 -0
  23. package/src/math/index.d.ts +21 -0
  24. package/src/math/index.js +39 -0
  25. package/src/math/index.ts +44 -0
  26. package/src/{operators.d.ts → operators/index.d.ts} +8 -6
  27. package/src/{operators.js → operators/index.js} +69 -26
  28. package/src/{operators.ts → operators/index.ts} +77 -28
  29. package/src/random/index.d.ts +42 -0
  30. package/src/random/index.js +65 -0
  31. package/src/random/index.ts +66 -0
  32. package/tests/collections.spec.ts +119 -30
  33. package/tests/globals.spec.ts +91 -49
  34. package/tests/itertools.spec.ts +207 -14
  35. package/tests/operators.spec.ts +7 -29
  36. package/tests/random.spec.ts +46 -0
  37. package/tsconfig.json +19 -3
  38. package/src/collections.d.ts +0 -224
  39. package/src/collections.js +0 -570
  40. package/src/collections.ts +0 -637
  41. package/src/datetime.d.ts +0 -1
  42. package/src/datetime.js +0 -1
  43. package/src/datetime.ts +0 -1
  44. package/src/globals.d.ts +0 -175
  45. package/src/globals.js +0 -329
  46. package/src/globals.ts +0 -373
  47. package/src/itertools.d.ts +0 -16
  48. package/src/itertools.js +0 -101
  49. package/src/itertools.ts +0 -112
  50. package/src/math.d.ts +0 -16
  51. package/src/math.js +0 -67
  52. package/src/math.ts +0 -73
  53. package/src/objects.d.ts +0 -0
  54. package/src/objects.js +0 -1
  55. package/src/objects.ts +0 -0
  56. package/src/random.d.ts +0 -22
  57. package/src/random.js +0 -48
  58. package/src/random.ts +0 -49
  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,485 @@
1
+ /**
2
+ * This module includes functions that deal with or produce iterators.
3
+ *
4
+ * @module Iterators
5
+ */
6
+ import { call, isEmpty, isObject, notNull, ValueError } from '../globals/index.js';
7
+ import { bool, comp, eq, gt, id, le, add } from '../operators/index.js';
8
+ /**
9
+ * Make an iterator that returns accumulated sums, or accumulated results of other binary functions (specified via the optional `func` argument).
10
+ * @param iterable The iterable to accumulate
11
+ * @param func The accumulator function (default `add`).
12
+ * @param initial Optional initial value (defaults to the first element in iterable)
13
+ * @returns A sequence of accumulated values
14
+ */
15
+ export function* accumulate(iterable, func = add, initial) {
16
+ const it = iter(iterable);
17
+ let total = initial;
18
+ let head = it.next();
19
+ if (initial == null)
20
+ total = head.value;
21
+ while (!head.done) {
22
+ yield total;
23
+ head = it.next();
24
+ if (head.done)
25
+ return;
26
+ total = func(total, head.value);
27
+ }
28
+ }
29
+ /**
30
+ * Returns `true` when all of the items in iterable are truthy. An optional predicate function can be used to define what truthiness means for this specific collection.
31
+ * @param iterable
32
+ * @param fn
33
+ * @returns `True` if all elements pass the test or are truthy else `false`.
34
+ * @example
35
+ ```js
36
+ all([0])
37
+ // => true
38
+
39
+ all([1, 2, 3])
40
+ // => true
41
+
42
+ all([2, 4, 6] => (n) => n > 1)
43
+ // => true
44
+ ```
45
+ @see {@link any}
46
+ */
47
+ export const all = (iterable, fn = bool) => {
48
+ for (const item of iterable) {
49
+ if (!fn(item))
50
+ return false;
51
+ }
52
+ return true;
53
+ };
54
+ /**
55
+ * Returns true when any of the items in iterable are truthy. An optional predicate function can be used to define what truthiness means for this specific collection.
56
+ * @param iterable
57
+ * @param fn
58
+ * @returns `True` if any element passes the test or is truthy else `false`.
59
+ * @example
60
+ ```js
61
+ any([0])
62
+ // => false
63
+
64
+ any([0, 1, null, undefined])
65
+ // => true
66
+
67
+ any([1, 4, 5] => (n) => n % 2 === 0)
68
+ // => true
69
+ ```
70
+ @see {@link all}
71
+ */
72
+ export const any = (iterable, fn = bool) => {
73
+ for (const item of iterable) {
74
+ if (fn(item))
75
+ return true;
76
+ }
77
+ return false;
78
+ };
79
+ export function chain(...iterables) {
80
+ return iflatten(iterables);
81
+ }
82
+ /**
83
+ * Checks if the `value` is in `collection`.
84
+ * @param collection The collection to inspect.
85
+ * @param value The value to search for.
86
+ * @returns Returns `true` if value is found, else `false`.
87
+ * @example
88
+ ```js
89
+ contains([1, 2, 3], 1)
90
+ // => true
91
+
92
+ contains([1, 2, 3], 1, 2)
93
+ // => false
94
+
95
+ contains({ 'a': 1, 'b': 2 }, 1)
96
+ // => true
97
+
98
+ contains('abcd', 'bc')
99
+ // => true
100
+ ```
101
+ *
102
+ * @see {@link collections.find}
103
+ */
104
+ export function contains(collection, value) {
105
+ if (!collection)
106
+ return false;
107
+ const includes = call(collection, 'includes', value);
108
+ if (includes != null)
109
+ return includes;
110
+ return any(collection, (x) => eq(value, x));
111
+ }
112
+ const compKey = (cmp, key) => (x, y) => cmp(key(x), key(y));
113
+ /**
114
+ * Returns a generator that drops elements from the iterable as long as the predicate is `true`; afterwards, returns every remaining element. Note, the generator does not produce any output until the predicate first becomes `false`.
115
+ * @param iterable The iterable to inspect.
116
+ * @param predicate A function invoked per element to check if it should be dropped.
117
+ * @returns Elements
118
+ */
119
+ export function* dropWhile(iterable, predicate) {
120
+ const it = iter(iterable);
121
+ while (true) {
122
+ const head = it.next();
123
+ if (!predicate(head.value)) {
124
+ if (head.done)
125
+ return head.value;
126
+ yield head.value;
127
+ break;
128
+ }
129
+ }
130
+ while (true) {
131
+ const head = it.next();
132
+ if (head.done)
133
+ return head.value;
134
+ yield head.value;
135
+ }
136
+ }
137
+ /**
138
+ * Yields elements like `[index, item]` from an iterable. Index starts at zero by default.
139
+ * @template T
140
+ * @param iterable The iterable to inspect.
141
+ * @param start The starting index.
142
+ * @returns A generator with tuples like `[index, item]`.
143
+ * @example
144
+ ```js
145
+ console.log([...enumerate(['hello', 'world'])])
146
+ // => [[0, 'hello'], [1, 'world']]
147
+
148
+ // Start with index `1`
149
+ console.log([...enumerate(['hello', 'world'], 1)])
150
+ // => [[1, 'hello'], [2, 'world']]
151
+ ```
152
+ */
153
+ export function* enumerate(iterable, start = 0) {
154
+ let index = start;
155
+ for (const item of iterable) {
156
+ yield [index++, item];
157
+ }
158
+ }
159
+ /**
160
+ * Returns the first element in an iterable.
161
+ * @param iterable The iterable to inspect.
162
+ * @returns The first element found or undefined if iterable is empty.
163
+ */
164
+ export function first(iterable) {
165
+ return iter(iterable).next().value;
166
+ }
167
+ /**
168
+ * Creates a new generator that filters all `falsey` and empty values from iterable.
169
+ * @param arr The array to compact
170
+ * @returns A new array with the filtered values.
171
+ * @example
172
+ ```js
173
+ compact([0, 1, false, 2, '', 3])
174
+ // => [1, 2, 3]
175
+ ```
176
+ */
177
+ export function* icompact(iterable) {
178
+ for (const value of iterable) {
179
+ if (!isEmpty(value))
180
+ yield value;
181
+ }
182
+ }
183
+ /**
184
+ * Iterates over elements of collection, producing only those elements where predicate returns a `truthy` value.
185
+ */
186
+ export function* ifilter(iterable, predicate) {
187
+ for (const value of iterable) {
188
+ if (predicate(value))
189
+ yield value;
190
+ }
191
+ }
192
+ export function* imap(iterable, mapFn) {
193
+ for (const item of iterable) {
194
+ yield mapFn(item);
195
+ }
196
+ }
197
+ /**
198
+ * Returns a generator flattening one level of nesting in a list of lists.
199
+ * @param iterables The iterable to flatten
200
+ * @example
201
+ ```js
202
+ [...iflatten([[0, 1], [2, 3]])]
203
+ // => [0, 1, 2, 3]
204
+ ```
205
+ */
206
+ export function* iflatten(iterables) {
207
+ for (const iterator of iterables) {
208
+ for (const item of iterator) {
209
+ yield item;
210
+ }
211
+ }
212
+ }
213
+ export function flatMap(iterable, mapFn = id) {
214
+ return iflatten(imap(iterable, mapFn));
215
+ }
216
+ export function* islice(iterable, start, stop, step = 1) {
217
+ if (stop != null && stop < 0)
218
+ throw new ValueError(`stop parameter can't be negative`);
219
+ if (start < 0)
220
+ throw new ValueError(`start parameter can't be negative`);
221
+ if (stop != null && start > stop)
222
+ throw new ValueError(`start parameter can't be after stop`);
223
+ if (step < 0)
224
+ throw new ValueError(`step parameter can't be negative`);
225
+ for (const [i, value] of enumerate(iterable)) {
226
+ if (i === start) {
227
+ if (stop && start + step > stop)
228
+ return value;
229
+ yield value;
230
+ start += step;
231
+ }
232
+ }
233
+ }
234
+ export function* itake(n, iterable) {
235
+ const it = iter(iterable);
236
+ while (n-- > 0) {
237
+ const item = it.next();
238
+ if (!item.done)
239
+ yield item.value;
240
+ else
241
+ return;
242
+ }
243
+ }
244
+ /**
245
+ * Returns an Iterator from the elements of a collection or the object keys.
246
+ * @param obj The given collection to iterate over.
247
+ * @returns An Iterator type.
248
+ */
249
+ export function iter(obj) {
250
+ const iterable = call(obj, Symbol.iterator);
251
+ if (notNull(iterable))
252
+ return iterable;
253
+ return Object.keys(obj)[Symbol.iterator]();
254
+ }
255
+ export function partition(iterable, predicate) {
256
+ const left = [];
257
+ const right = [];
258
+ for (const value of iterable) {
259
+ if (predicate(value))
260
+ left.push(value);
261
+ else
262
+ right.push(value);
263
+ }
264
+ return [left, right];
265
+ }
266
+ /**
267
+ * Returns the smallest element in an iterable. The optional `key` argument specifies a transform on the elements before comparing them. If the elements in the iterable are objects that implement a custom `le` method, this will be called to compare.
268
+ * @param iterable The iterable to inspect.
269
+ * @param key Optional key function to transform the elements (default `id`).
270
+ * @returns The smallest element in the iterable.
271
+ */
272
+ export function min(iterable, key = id) {
273
+ return reduce(iterable, (x, y) => (le(key(x), key(y)) ? x : y));
274
+ }
275
+ /**
276
+ * Returns the largest element in an iterable. The optional `key` argument specifies a transform on the elements before comparing them. If the elements in the iterable are objects that implement a custom `gt` method, this will be called to compare.
277
+ * @param iterable The iterable to inspect.
278
+ * @param key Optional key function to transform the elements (default `id`).
279
+ * @returns The largest element in the iterable.
280
+ */
281
+ export function max(iterable, key = id) {
282
+ return reduce(iterable, (x, y) => (gt(key(x), key(y)) ? x : y));
283
+ }
284
+ /**
285
+ * Returns a generator for a sequence of numbers in the given range, starting from `start` (default 0) to `stop` (not-inclusive) in increments of `step` (default 1).
286
+ *
287
+ * `range(x)` is a shorthand for `range(0, x, 1)`.
288
+ * @param args When called with a single argument, it is assigned to `stop` param. If two arguments are given, it will assign them to `(start, stop)`. When three arguments, it means `(start, stop, step)`.
289
+ * @example
290
+ ```js
291
+ range(5)
292
+ // => [0, 1, 2, 3, 4]
293
+
294
+ range(2, 5)
295
+ // => [2, 3, 4]
296
+
297
+ range(0, 5, 2)
298
+ // => [0, 2, 4]
299
+
300
+ range(5, 0, -1)
301
+ // => [5, 4, 3, 2, 1]
302
+
303
+ range(-3)
304
+ // => []
305
+ ```
306
+ */
307
+ export function* range(...args) {
308
+ let start = 0;
309
+ let stop = 0;
310
+ let step = 1;
311
+ if (args.length === 1) {
312
+ stop = args[0];
313
+ }
314
+ else if (args.length === 2) {
315
+ start = args[0];
316
+ stop = args[1];
317
+ }
318
+ else {
319
+ start = args[0];
320
+ stop = args[1];
321
+ step = args[2] || 1;
322
+ }
323
+ for (; step > 0 ? start < stop : start > stop; start += step) {
324
+ yield start;
325
+ }
326
+ }
327
+ /**
328
+ * Applies a `reducer` function on each element of the iterable, in order, passing the return value from the operation on the previous element. The final result of running the reducer across all elements of the iterable is a single value.
329
+ * @param iterable The collection to reduce.
330
+ * @param reducer A reducer function that will be called per item.
331
+ * @param initial Optional initial value (defaults to the first element in the iterable).
332
+ * @returns The result of calling reducer on each item.
333
+ * @example
334
+ ```js
335
+ reduce([1, 2, 3, 4, 5], (x, y) => x + y, 0)
336
+ // => 15
337
+ ```
338
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce Array.reduce()}
339
+ */
340
+ export function reduce(iterable, reducer, initial) {
341
+ const it = iter(iterable);
342
+ let output = initial ?? it.next().value;
343
+ for (const [index, value] of enumerate(it)) {
344
+ output = reducer(output, value, index);
345
+ }
346
+ return output;
347
+ }
348
+ /**
349
+ * Creates a new array with the elements from the iterable in reverse order.
350
+ * @param iterable The iterable to inspect.
351
+ * @returns A new array with the elements reversed.
352
+ */
353
+ export function reversed(iterable) {
354
+ return Array.from(iterable).reverse();
355
+ }
356
+ /**
357
+ * Creates a new sorted list from the elements in the array. This can be called many ways:
358
+ * - sorted([...], true) => reverse order
359
+ * - sorted([...], fn = (x) => any) => using a key fn
360
+ * - sorted([...], fn = (x) => any, true) => reverse order using key
361
+ * - sorted([...], false, (x, y) => number) => using custom compare
362
+ * - sorted([...], fn = (x) => any, true, (x, y) => number) => custom key, reverse and compare
363
+ *
364
+ * If `args` is an Object, returns the sorted keys.
365
+ *
366
+ *
367
+ * @param {(Array | Object)} args
368
+ * @param {(boolean | Function)} [key]
369
+ * @param {(boolean | Comp)} [reverse]
370
+ * @param {Comp} [compareFn]
371
+ * @return
372
+ */
373
+ export function sorted(args, key, reverse, compareFn) {
374
+ if (isObject(args))
375
+ args = Object.keys(args);
376
+ if (typeof key === 'boolean') {
377
+ if (typeof reverse === 'function') {
378
+ compareFn = reverse;
379
+ reverse = false;
380
+ }
381
+ else {
382
+ reverse = true;
383
+ }
384
+ key = id;
385
+ }
386
+ const copy = Array.from(args);
387
+ const _compare = compKey(compareFn || comp, key || id);
388
+ copy.sort(_compare);
389
+ if (reverse)
390
+ copy.reverse();
391
+ return copy;
392
+ }
393
+ /**
394
+ * Sort `args` in place. Can be called like this:
395
+ * - sort([...], true) => reverse order
396
+ * - sort([...], (x, y) => number) => using custom compare
397
+ * - sort([...], true, (x, y) => number) => reverse and using custom compare
398
+ *
399
+ * @param {any[]} args
400
+ * @param {(boolean | Comp)} [reverse]
401
+ * @param {Comp} [compareFn]
402
+ * @return
403
+ */
404
+ export function sort(args, reverse, compareFn) {
405
+ if (typeof reverse === 'function') {
406
+ compareFn = reverse;
407
+ reverse = false;
408
+ }
409
+ args.sort(compareFn || comp);
410
+ if (reverse === true)
411
+ args.reverse();
412
+ return args;
413
+ }
414
+ /**
415
+ * Sums `initial` and the items of an iterable and returns the total.
416
+ * @param args The elements to add to `initial`.
417
+ * @param initial The initial value to add to (default `0`).
418
+ * @returns The total sum of initial and iterable elements.
419
+ * @example
420
+ ```js
421
+ sum([1, 2, 3, 4])
422
+ // => 10
423
+
424
+ sum([1, 2, 3, 4], 5)
425
+ // => 15
426
+ ```
427
+ */
428
+ export function sum(args, initial = 0) {
429
+ for (const x of args) {
430
+ initial += x;
431
+ }
432
+ return initial;
433
+ }
434
+ export function take(n, iterable) {
435
+ return [...itake(n, iterable)];
436
+ }
437
+ /**
438
+ * Returns a generator that takes elements from the iterable as long as the predicate is `true`.
439
+ * @param iterable The iterable to inspect.
440
+ * @param predicate A function invoked per element to check if it should be taken.
441
+ * @returns Elements
442
+ */
443
+ export function* takeWhile(iterable, predicate) {
444
+ for (const value of iterable) {
445
+ if (!predicate(value))
446
+ return;
447
+ yield value;
448
+ }
449
+ }
450
+ /** Returns a generator that calls `fn(index)` for each index < n */
451
+ /**
452
+ * Returns a generator that produces `fn(index)` for each `index < n`.
453
+ * @param n The number of times to invoke `fn`.
454
+ * @param fn A function used to produce the results.
455
+ */
456
+ export function* times(n, fn) {
457
+ for (let i = 0; i < n; i++)
458
+ yield fn(i);
459
+ }
460
+ /**
461
+ * Returns a generator that aggregates elements from the iterables producing tuples with the next element from each one.
462
+ * @param args The iterables to zip
463
+ * @returns Tuples with elements from each iterator
464
+ * @example
465
+ ```js
466
+ for item of zip([1, 2, 3], ['sugar', 'spice', 'nice'])
467
+ console.log(item)
468
+ // => [1, 'sugar']
469
+ // => [2, 'spice']
470
+ // => [3, 'nice']
471
+ ```
472
+ */
473
+ export function* zip(...args) {
474
+ const iterables = args.map(iter);
475
+ while (true) {
476
+ const items = [];
477
+ for (const iterator of iterables) {
478
+ const { value, done } = iterator.next();
479
+ if (done)
480
+ return;
481
+ items.push(value);
482
+ }
483
+ yield items;
484
+ }
485
+ }