atomic-fns 0.2.2 → 0.3.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.
Files changed (70) hide show
  1. package/.firebaserc +5 -0
  2. package/README.md +9 -4
  3. package/firebase.json +10 -0
  4. package/package.json +9 -9
  5. package/src/collections/index.d.ts +672 -0
  6. package/src/collections/index.js +1091 -0
  7. package/src/collections/index.ts +1186 -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/index.d.ts +107 -0
  12. package/src/functools/index.js +219 -0
  13. package/src/functools/index.ts +255 -0
  14. package/src/globals/index.d.ts +286 -0
  15. package/src/globals/index.js +388 -0
  16. package/src/globals/index.ts +451 -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 +225 -0
  21. package/src/itertools/index.js +449 -0
  22. package/src/itertools/index.ts +471 -0
  23. package/src/math/index.d.ts +97 -0
  24. package/src/math/index.js +92 -0
  25. package/src/math/index.ts +152 -0
  26. package/src/{operators.d.ts → operators/index.d.ts} +11 -9
  27. package/src/operators/index.js +171 -0
  28. package/src/operators/index.ts +175 -0
  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 +42 -25
  33. package/tests/globals.spec.ts +56 -60
  34. package/tests/itertools.spec.ts +176 -4
  35. package/tests/math.spec.ts +25 -0
  36. package/tests/operators.spec.ts +1 -26
  37. package/tests/random.spec.ts +46 -0
  38. package/tsconfig.json +12 -4
  39. package/src/collections.d.ts +0 -228
  40. package/src/collections.js +0 -553
  41. package/src/collections.ts +0 -641
  42. package/src/datetime.d.ts +0 -5
  43. package/src/datetime.js +0 -5
  44. package/src/datetime.ts +0 -6
  45. package/src/functools.d.ts +0 -40
  46. package/src/functools.js +0 -78
  47. package/src/functools.ts +0 -93
  48. package/src/globals.d.ts +0 -179
  49. package/src/globals.js +0 -309
  50. package/src/globals.ts +0 -377
  51. package/src/itertools.d.ts +0 -20
  52. package/src/itertools.js +0 -98
  53. package/src/itertools.ts +0 -116
  54. package/src/math.d.ts +0 -16
  55. package/src/math.js +0 -70
  56. package/src/math.ts +0 -77
  57. package/src/objects.d.ts +0 -0
  58. package/src/objects.js +0 -1
  59. package/src/objects.ts +0 -0
  60. package/src/operators.js +0 -109
  61. package/src/operators.ts +0 -130
  62. package/src/random.d.ts +0 -22
  63. package/src/random.js +0 -48
  64. package/src/random.ts +0 -53
  65. package/src/strings.d.ts +0 -0
  66. package/src/strings.js +0 -1
  67. package/src/strings.ts +0 -0
  68. package/src/util.d.ts +0 -0
  69. package/src/util.js +0 -1
  70. package/src/util.ts +0 -0
@@ -0,0 +1,225 @@
1
+ /**
2
+ * This module includes functions that deal with or produce iterators.
3
+ *
4
+ * @module Iterators
5
+ */
6
+ import { Comp, Function, Predicate } from '../globals/index.js';
7
+ import { 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 declare function accumulate<T>(iterable: Iterable<T>, func?: typeof add, initial?: any): Generator<any, void, unknown>;
16
+ /**
17
+ * 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.
18
+ * @param iterable
19
+ * @param fn
20
+ * @returns `True` if all elements pass the test or are truthy else `false`.
21
+ * @example
22
+ ```js
23
+ all([0])
24
+ // => true
25
+
26
+ all([1, 2, 3])
27
+ // => true
28
+
29
+ all([2, 4, 6] => (n) => n > 1)
30
+ // => true
31
+ ```
32
+ @see {@link any}
33
+ */
34
+ export declare const all: <T>(iterable: Iterable<T>, fn?: Predicate<T>) => boolean;
35
+ /**
36
+ * 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.
37
+ * @param iterable
38
+ * @param fn
39
+ * @returns `True` if any element passes the test or is truthy else `false`.
40
+ * @example
41
+ ```js
42
+ any([0])
43
+ // => false
44
+
45
+ any([0, 1, null, undefined])
46
+ // => true
47
+
48
+ any([1, 4, 5] => (n) => n % 2 === 0)
49
+ // => true
50
+ ```
51
+ @see {@link all}
52
+ */
53
+ export declare const any: <T>(iterable: Iterable<T>, fn?: Predicate<T>) => boolean;
54
+ export declare function chain<T>(...iterables: Array<Iterable<T>>): Generator<T, void, unknown>;
55
+ /**
56
+ * Checks if the `value` is in `collection`.
57
+ * @param collection The collection to inspect.
58
+ * @param value The value to search for.
59
+ * @returns Returns `true` if value is found, else `false`.
60
+ * @example
61
+ ```js
62
+ contains([1, 2, 3], 1)
63
+ // => true
64
+
65
+ contains([1, 2, 3], 1, 2)
66
+ // => false
67
+
68
+ contains({ 'a': 1, 'b': 2 }, 1)
69
+ // => true
70
+
71
+ contains('abcd', 'bc')
72
+ // => true
73
+ ```
74
+ *
75
+ * @see {@link Collections.find}
76
+ */
77
+ export declare function contains(collection: Iterable<any>, value: any): any;
78
+ /**
79
+ * 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`.
80
+ * @param iterable The iterable to inspect.
81
+ * @param predicate A function invoked per element to check if it should be dropped.
82
+ * @returns Elements
83
+ */
84
+ export declare function dropWhile<T>(iterable: Iterable<T>, predicate: Predicate): Generator<unknown, any, unknown>;
85
+ /**
86
+ * Yields elements like `[index, item]` from an iterable. Index starts at zero by default.
87
+ * @template T
88
+ * @param iterable The iterable to inspect.
89
+ * @param start The starting index.
90
+ * @returns A generator with tuples like `[index, item]`.
91
+ * @example
92
+ ```js
93
+ console.log([...enumerate(['hello', 'world'])])
94
+ // => [[0, 'hello'], [1, 'world']]
95
+
96
+ // Start with index `1`
97
+ console.log([...enumerate(['hello', 'world'], 1)])
98
+ // => [[1, 'hello'], [2, 'world']]
99
+ ```
100
+ */
101
+ export declare function enumerate<T = any>(iterable: Iterable<T>, start?: number): Generator<(number | T)[], void, unknown>;
102
+ /**
103
+ * Returns the first element in an iterable.
104
+ * @param iterable The iterable to inspect.
105
+ * @returns The first element found or undefined if iterable is empty.
106
+ */
107
+ export declare function first<T>(iterable: Iterable<T>): any;
108
+ /**
109
+ * Creates a new generator that filters all `falsey` and empty values from iterable.
110
+ * @param arr The array to compact
111
+ * @returns A new array with the filtered values.
112
+ * @example
113
+ ```js
114
+ compact([0, 1, false, 2, '', 3])
115
+ // => [1, 2, 3]
116
+ ```
117
+ */
118
+ export declare function icompact<T>(iterable: Iterable<T>): Generator<T, void, unknown>;
119
+ /**
120
+ * Iterates over elements of collection, producing only those elements where predicate returns a `truthy` value.
121
+ */
122
+ export declare function ifilter<T>(iterable: Iterable<T>, predicate: Predicate): Generator<T, void, unknown>;
123
+ export declare function imap<T>(iterable: Iterable<T>, mapFn: (x: T) => any): Generator<any, void, unknown>;
124
+ /**
125
+ * Returns a generator flattening one level of nesting in a list of lists.
126
+ * @param iterables The iterable to flatten
127
+ * @example
128
+ ```js
129
+ [...iflatten([[0, 1], [2, 3]])]
130
+ // => [0, 1, 2, 3]
131
+ ```
132
+ */
133
+ export declare function iflatten<T = any>(iterables: Iterable<Iterable<T>>): Generator<T, void, unknown>;
134
+ export declare function flatMap<T>(iterable: Iterable<T>, mapFn?: (x: T) => any): Generator<T, void, unknown>;
135
+ export declare function islice<T>(iterable: Iterable<T>, start: number, stop?: number, step?: number): Generator<number | T, number | T | undefined, unknown>;
136
+ export declare function itake<T>(n: number, iterable: Iterable<T>): Generator<unknown, void, unknown>;
137
+ /**
138
+ * Returns an Iterator from the elements of a collection or the object keys.
139
+ * @param obj The given collection to iterate over.
140
+ * @returns An Iterator type.
141
+ */
142
+ export declare function iter<T>(obj: any): Iterator<T>;
143
+ export declare function partition<T>(iterable: Iterable<T>, predicate: Predicate<T>): T[][];
144
+ /**
145
+ * 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).
146
+ *
147
+ * `range(x)` is a shorthand for `range(0, x, 1)`.
148
+ * @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)`.
149
+ * @example
150
+ ```js
151
+ range(5)
152
+ // => [0, 1, 2, 3, 4]
153
+
154
+ range(2, 5)
155
+ // => [2, 3, 4]
156
+
157
+ range(0, 5, 2)
158
+ // => [0, 2, 4]
159
+
160
+ range(5, 0, -1)
161
+ // => [5, 4, 3, 2, 1]
162
+
163
+ range(-3)
164
+ // => []
165
+ ```
166
+ */
167
+ export declare function range(...args: number[]): Generator<number, void, unknown>;
168
+ /**
169
+ * 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.
170
+ * @param iterable The collection to reduce.
171
+ * @param reducer A reducer function that will be called per item.
172
+ * @param initial Optional initial value (defaults to the first element in the iterable).
173
+ * @returns The result of calling reducer on each item.
174
+ * @example
175
+ ```js
176
+ reduce([1, 2, 3, 4, 5], (x, y) => x + y, 0)
177
+ // => 15
178
+ ```
179
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce Array.reduce()}
180
+ */
181
+ export declare function reduce<T>(iterable: Iterable<T>, reducer: (prev: T, value: T, index: any) => T, initial?: any): any;
182
+ /**
183
+ * Creates a new array with the elements from the iterable in reverse order.
184
+ * @param iterable The iterable to inspect.
185
+ * @returns A new array with the elements reversed.
186
+ */
187
+ export declare function reversed<T>(iterable: Iterable<T>): T[];
188
+ export declare function sorted(args: any[]): any[];
189
+ export declare function sorted(args: any[], reverse: boolean): any[];
190
+ export declare function sorted(args: any[], reverse: boolean, comp: Comp): any[];
191
+ export declare function sorted(args: any[], key: Function): any[];
192
+ export declare function sorted(args: any[], key: Function, reverse: boolean): any[];
193
+ export declare function sort(args: any[]): any[];
194
+ export declare function sort(args: any[], reverse: boolean): any[];
195
+ export declare function sort(args: any[], compareFn: Comp): any[];
196
+ export declare function sort(args: any[], reverse: boolean, compareFn: Comp): any[];
197
+ export declare function take<T>(n: number, iterable: Iterable<T>): unknown[];
198
+ /**
199
+ * Returns a generator that takes elements from the iterable as long as the predicate is `true`.
200
+ * @param iterable The iterable to inspect.
201
+ * @param predicate A function invoked per element to check if it should be taken.
202
+ * @returns Elements
203
+ */
204
+ export declare function takeWhile<T>(iterable: Iterable<T>, predicate: Predicate): Generator<T, void, unknown>;
205
+ /** Returns a generator that calls `fn(index)` for each index < n */
206
+ /**
207
+ * Returns a generator that produces `fn(index)` for each `index < n`.
208
+ * @param n The number of times to invoke `fn`.
209
+ * @param fn A function used to produce the results.
210
+ */
211
+ export declare function times(n: number, fn: (index: number) => any): Generator<any, void, unknown>;
212
+ /**
213
+ * Returns a generator that aggregates elements from the iterables producing tuples with the next element from each one.
214
+ * @param args The iterables to zip
215
+ * @returns Tuples with elements from each iterator
216
+ * @example
217
+ ```js
218
+ for item of zip([1, 2, 3], ['sugar', 'spice', 'nice'])
219
+ console.log(item)
220
+ // => [1, 'sugar']
221
+ // => [2, 'spice']
222
+ // => [3, 'nice']
223
+ ```
224
+ */
225
+ export declare function zip(...args: Array<Iterable<any>>): Generator<any[], void, unknown>;
@@ -0,0 +1,449 @@
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 { add, bool, comp, eq, id } 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 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).
268
+ *
269
+ * `range(x)` is a shorthand for `range(0, x, 1)`.
270
+ * @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)`.
271
+ * @example
272
+ ```js
273
+ range(5)
274
+ // => [0, 1, 2, 3, 4]
275
+
276
+ range(2, 5)
277
+ // => [2, 3, 4]
278
+
279
+ range(0, 5, 2)
280
+ // => [0, 2, 4]
281
+
282
+ range(5, 0, -1)
283
+ // => [5, 4, 3, 2, 1]
284
+
285
+ range(-3)
286
+ // => []
287
+ ```
288
+ */
289
+ export function* range(...args) {
290
+ let start = 0;
291
+ let stop = 0;
292
+ let step = 1;
293
+ if (args.length === 1) {
294
+ stop = args[0];
295
+ if (stop < 0)
296
+ step = -1;
297
+ }
298
+ else if (args.length === 2) {
299
+ start = args[0];
300
+ stop = args[1];
301
+ }
302
+ else {
303
+ start = args[0];
304
+ stop = args[1];
305
+ step = args[2] || 1;
306
+ }
307
+ for (; step > 0 ? start < stop : start > stop; start += step) {
308
+ yield start;
309
+ }
310
+ }
311
+ /**
312
+ * 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.
313
+ * @param iterable The collection to reduce.
314
+ * @param reducer A reducer function that will be called per item.
315
+ * @param initial Optional initial value (defaults to the first element in the iterable).
316
+ * @returns The result of calling reducer on each item.
317
+ * @example
318
+ ```js
319
+ reduce([1, 2, 3, 4, 5], (x, y) => x + y, 0)
320
+ // => 15
321
+ ```
322
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce Array.reduce()}
323
+ */
324
+ export function reduce(iterable, reducer, initial) {
325
+ const it = iter(iterable);
326
+ let output = initial ?? it.next().value;
327
+ for (const [index, value] of enumerate(it)) {
328
+ output = reducer(output, value, index);
329
+ }
330
+ return output;
331
+ }
332
+ /**
333
+ * Creates a new array with the elements from the iterable in reverse order.
334
+ * @param iterable The iterable to inspect.
335
+ * @returns A new array with the elements reversed.
336
+ */
337
+ export function reversed(iterable) {
338
+ return Array.from(iterable).reverse();
339
+ }
340
+ /**
341
+ * Creates a new sorted list from the elements in the array. This can be called many ways:
342
+ * - sorted([...], true) => reverse order
343
+ * - sorted([...], fn = (x) => any) => using a key fn
344
+ * - sorted([...], fn = (x) => any, true) => reverse order using key
345
+ * - sorted([...], false, (x, y) => number) => using custom compare
346
+ * - sorted([...], fn = (x) => any, true, (x, y) => number) => custom key, reverse and compare
347
+ *
348
+ * If `args` is an Object, returns the sorted keys.
349
+ *
350
+ *
351
+ * @param {(Array | Object)} args
352
+ * @param {(boolean | Function)} [key]
353
+ * @param {(boolean | Comp)} [reverse]
354
+ * @param {Comp} [compareFn]
355
+ * @return
356
+ */
357
+ export function sorted(args, key, reverse, compareFn) {
358
+ if (isObject(args))
359
+ args = Object.keys(args);
360
+ if (typeof key === 'boolean') {
361
+ if (typeof reverse === 'function') {
362
+ compareFn = reverse;
363
+ reverse = false;
364
+ }
365
+ else {
366
+ reverse = true;
367
+ }
368
+ key = id;
369
+ }
370
+ const copy = Array.from(args);
371
+ const _compare = compKey(compareFn || comp, key || id);
372
+ copy.sort(_compare);
373
+ if (reverse)
374
+ copy.reverse();
375
+ return copy;
376
+ }
377
+ /**
378
+ * Sort `args` in place. Can be called like this:
379
+ * - sort([...], true) => reverse order
380
+ * - sort([...], (x, y) => number) => using custom compare
381
+ * - sort([...], true, (x, y) => number) => reverse and using custom compare
382
+ *
383
+ * @param {any[]} args
384
+ * @param {(boolean | Comp)} [reverse]
385
+ * @param {Comp} [compareFn]
386
+ * @return
387
+ */
388
+ export function sort(args, reverse, compareFn) {
389
+ if (typeof reverse === 'function') {
390
+ compareFn = reverse;
391
+ reverse = false;
392
+ }
393
+ args.sort(compareFn || comp);
394
+ if (reverse === true)
395
+ args.reverse();
396
+ return args;
397
+ }
398
+ export function take(n, iterable) {
399
+ return [...itake(n, iterable)];
400
+ }
401
+ /**
402
+ * Returns a generator that takes elements from the iterable as long as the predicate is `true`.
403
+ * @param iterable The iterable to inspect.
404
+ * @param predicate A function invoked per element to check if it should be taken.
405
+ * @returns Elements
406
+ */
407
+ export function* takeWhile(iterable, predicate) {
408
+ for (const value of iterable) {
409
+ if (!predicate(value))
410
+ return;
411
+ yield value;
412
+ }
413
+ }
414
+ /** Returns a generator that calls `fn(index)` for each index < n */
415
+ /**
416
+ * Returns a generator that produces `fn(index)` for each `index < n`.
417
+ * @param n The number of times to invoke `fn`.
418
+ * @param fn A function used to produce the results.
419
+ */
420
+ export function* times(n, fn) {
421
+ for (let i = 0; i < n; i++)
422
+ yield fn(i);
423
+ }
424
+ /**
425
+ * Returns a generator that aggregates elements from the iterables producing tuples with the next element from each one.
426
+ * @param args The iterables to zip
427
+ * @returns Tuples with elements from each iterator
428
+ * @example
429
+ ```js
430
+ for item of zip([1, 2, 3], ['sugar', 'spice', 'nice'])
431
+ console.log(item)
432
+ // => [1, 'sugar']
433
+ // => [2, 'spice']
434
+ // => [3, 'nice']
435
+ ```
436
+ */
437
+ export function* zip(...args) {
438
+ const iterables = args.map(iter);
439
+ while (true) {
440
+ const items = [];
441
+ for (const iterator of iterables) {
442
+ const { value, done } = iterator.next();
443
+ if (done)
444
+ return;
445
+ items.push(value);
446
+ }
447
+ yield items;
448
+ }
449
+ }