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