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
package/src/functools.js DELETED
@@ -1,78 +0,0 @@
1
- export const bind = (fn, self, ...args) => fn.bind(self, ...args)
2
- export const partial = (fn, ...args) => bind(fn, {}, ...args)
3
- export const flow =
4
- (...args) =>
5
- (x) => {
6
- for (const fn of args) {
7
- x = fn(x)
8
- }
9
- return x
10
- }
11
- export const pipe = flow
12
- export const compose = (...args) => flow(args.reverse())
13
- /**
14
- * Creates a function that memoizes the result of `func`. If `resolver` is provided, it determines the cache key for storing the result based on the arguments provided to the memoized function. By default, the first argument provided to the memoized function is used as the map cache key.
15
- *
16
- *
17
- * @param {Function} func The function to have its output memoized.
18
- * @param {Function} [resolver] The function to resolve the cache key.
19
- * @return {Function} Returns the new memoized function.
20
- */
21
- export function memoize(func, resolver) {
22
- const cache = new Map()
23
- return (...args) => {
24
- const key = resolver ? resolver(...args) : args[0]
25
- const prev = cache.get(key)
26
- if (prev !== undefined) return prev
27
- const value = func(...args)
28
- cache.set(key, value)
29
- return value
30
- }
31
- }
32
- /**
33
- * Creates a debounced function that delays invoking `func` until after `wait` milliseconds have elapsed since the last time the debounced function was invoked. Subsequent calls to the debounced function return the result of the last successful invocation. Provide options to set the `maxWait` milliseconds, regardless of when the function was last invoked.
34
- *
35
- *
36
- * @param {Function} func The function to debounce.
37
- * @param {number} wait The number of milliseconds to delay.
38
- * @param {{ maxWait: number }} { maxWait } The maximum time `func` is allowed to be delayed before it's invoked.
39
- * @return {Function} Returns the new debounced function.
40
- */
41
- export function debounce(func, wait, { maxWait }) {
42
- let timer, maxTimer, lastResult
43
- return (...args) => {
44
- if (timer) clearTimeout(timer)
45
- timer = setTimeout(() => {
46
- clearTimeout(maxTimer)
47
- maxTimer = null
48
- lastResult = func(...args)
49
- }, wait)
50
- if (maxWait && !maxTimer) {
51
- maxTimer = setTimeout(() => {
52
- clearTimeout(timer)
53
- maxTimer = null
54
- lastResult = func(...args)
55
- }, maxWait)
56
- }
57
- return lastResult
58
- }
59
- }
60
- /**
61
- * Creates a throttled function that only invokes `func` at most once per every `wait` milliseconds. Subsequent calls to the throttled function return the result of the last successful invocation.
62
- *
63
- *
64
- * @param {Function} func The function to throttle.
65
- * @param {number} time The number of milliseconds to throttle invocations to.
66
- * @return {Function} Returns the new throttled function.
67
- */
68
- export function throttle(func, time) {
69
- let pending = false
70
- return (...args) => {
71
- if (pending) return
72
- func(...args)
73
- pending = true
74
- setTimeout(() => {
75
- pending = false
76
- }, time)
77
- }
78
- }
package/src/functools.ts DELETED
@@ -1,93 +0,0 @@
1
- /**
2
- * FP
3
- * @module
4
- */
5
- import { Function } from './globals.js'
6
-
7
- export const bind = (fn, self, ...args) => fn.bind(self, ...args)
8
-
9
- export const partial = (fn, ...args) => bind(fn, {}, ...args)
10
-
11
- export const flow =
12
- (...args) =>
13
- (x: any) => {
14
- for (const fn of args) {
15
- x = fn(x)
16
- }
17
- return x
18
- }
19
-
20
- export const pipe = flow
21
-
22
- export const compose = (...args) => flow(args.reverse())
23
-
24
- /**
25
- * Creates a function that memoizes the result of `func`. If `resolver` is provided, it determines the cache key for storing the result based on the arguments provided to the memoized function. By default, the first argument provided to the memoized function is used as the map cache key.
26
- *
27
- *
28
- * @param {Function} func The function to have its output memoized.
29
- * @param {Function} [resolver] The function to resolve the cache key.
30
- * @return {Function} Returns the new memoized function.
31
- */
32
- export function memoize(func: Function, resolver?: Function): Function {
33
- const cache = new Map()
34
- return (...args) => {
35
- const key = resolver ? resolver(...args) : args[0]
36
- const prev = cache.get(key)
37
- if (prev !== undefined) return prev
38
- const value = func(...args)
39
- cache.set(key, value)
40
- return value
41
- }
42
- }
43
-
44
- /**
45
- * Creates a debounced function that delays invoking `func` until after `wait` milliseconds have elapsed since the last time the debounced function was invoked. Subsequent calls to the debounced function return the result of the last successful invocation. Provide options to set the `maxWait` milliseconds, regardless of when the function was last invoked.
46
- *
47
- *
48
- * @param {Function} func The function to debounce.
49
- * @param {number} wait The number of milliseconds to delay.
50
- * @param {{ maxWait: number }} { maxWait } The maximum time `func` is allowed to be delayed before it's invoked.
51
- * @return {Function} Returns the new debounced function.
52
- */
53
- export function debounce(func: Function, wait: number, { maxWait }: { maxWait: number }): Function {
54
- let timer, maxTimer, lastResult
55
- return (...args) => {
56
- if (timer) clearTimeout(timer)
57
- timer = setTimeout(() => {
58
- clearTimeout(maxTimer)
59
- maxTimer = null
60
- lastResult = func(...args)
61
- }, wait)
62
-
63
- if (maxWait && !maxTimer) {
64
- maxTimer = setTimeout(() => {
65
- clearTimeout(timer)
66
- maxTimer = null
67
- lastResult = func(...args)
68
- }, maxWait)
69
- }
70
-
71
- return lastResult
72
- }
73
- }
74
-
75
- /**
76
- * Creates a throttled function that only invokes `func` at most once per every `wait` milliseconds. Subsequent calls to the throttled function return the result of the last successful invocation.
77
- *
78
- *
79
- * @param {Function} func The function to throttle.
80
- * @param {number} time The number of milliseconds to throttle invocations to.
81
- * @return {Function} Returns the new throttled function.
82
- */
83
- export function throttle(func: Function, time: number): Function {
84
- let pending = false
85
- return (...args) => {
86
- if (pending) return
87
- func(...args)
88
- pending = true
89
- setTimeout(() => {
90
- pending = false
91
- }, time)
92
- }
93
- }
package/src/globals.d.ts DELETED
@@ -1,179 +0,0 @@
1
- /**
2
- * Globals
3
- * @module
4
- */
5
- export declare type Comp = (x: any, y: any) => number;
6
- export declare type Function = (...args: any[]) => any;
7
- export declare type Iteratee = (value: any, key?: any, arr?: any) => any;
8
- export declare const True: () => boolean;
9
- export declare const False: () => boolean;
10
- /**
11
- * A custom error class that inherits from the Error object.
12
- *
13
- *
14
- * @class CustomError
15
- * @extends {Error}
16
- */
17
- export declare class CustomError extends Error {
18
- /**
19
- * Returns a new CustomError with the specified message.
20
- * @param {string} message
21
- * @constructor
22
- */
23
- constructor(message?: string);
24
- }
25
- /**
26
- * Custom error to signal an invalid index access.
27
- * @extends {CustomError}
28
- */
29
- export declare class IndexError extends CustomError {
30
- }
31
- /**
32
- * Raised when a system function returns an I/O failure such as "file not found"
33
- * or "disk full".
34
- * @extends {CustomError}
35
- */
36
- export declare class IOError extends CustomError {
37
- }
38
- /**
39
- * Custom error to signal an invalid key access.
40
- * @extends {CustomError}
41
- */
42
- export declare class KeyError extends CustomError {
43
- }
44
- /**
45
- * Custom error to signal an invalid operation.
46
- * @extends {CustomError}
47
- */
48
- export declare class NotImplementedError extends CustomError {
49
- }
50
- /**
51
- * Custom error to signal an invalid value.
52
- * @extends {CustomError}
53
- */
54
- export declare class ValueError extends CustomError {
55
- }
56
- /**
57
- * Raised when the second argument of a division or modulo operation is zero.
58
- * @extends {CustomError}
59
- */
60
- export declare class ZeroDivisionError extends CustomError {
61
- }
62
- /**
63
- * Returns the true type of any value with correct detection for null, Array,
64
- * Object, Promise, Symbol, and NaN.
65
- *
66
- *
67
- * @param {*} value
68
- * @return
69
- */
70
- export declare function type(value: any): "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" | "array" | "promise" | "null" | "NaN";
71
- /** Same as `x.toString()`. Returns `''` when x is null or undefined */
72
- export declare const str: (x: any) => any;
73
- /** Check if value is a boolean type */
74
- export declare const isBool: (x: any) => boolean;
75
- /** Check if value is an object type */
76
- export declare const isObject: (x: any) => boolean;
77
- /** Check if value is a string type */
78
- export declare const isString: (x: any) => boolean;
79
- /** Check if value is an Array type */
80
- export declare const isArray: (x: any) => boolean;
81
- /** Check if value is Array-like type.
82
- * A value is considered array-like if it's not a function and has a
83
- * `.length` number property.
84
- */
85
- export declare const isArrayLike: (x: any) => boolean;
86
- /** Check if value is a function type */
87
- export declare const isFunc: (x: any) => boolean;
88
- /** Check if value is a number type */
89
- export declare const isNumber: (x: any) => boolean;
90
- /** Check if value is a Bigint type */
91
- export declare const isBigint: (x: any) => boolean;
92
- /** Check if value is NaN based on `Number.isNaN` */
93
- export declare const isNaN: (x: any) => boolean;
94
- /** Check if value is a Promise type */
95
- export declare const isPromise: (x: any) => boolean;
96
- /** Check if value is an async function type */
97
- export declare const isAsync: (x: any) => boolean;
98
- /** Check if value is a generator function type */
99
- export declare const isGenerator: (x: any) => boolean;
100
- /** Check if value is null or undefined */
101
- export declare const isNull: (x: any) => boolean;
102
- /** Check if value is not null or undefined */
103
- export declare const notNull: (x: any) => boolean;
104
- export declare function len(x: any): any;
105
- /** Returns true for objects without length or falsey values. */
106
- export declare const isEmpty: (x: any) => boolean;
107
- /** Check if value is a Symbol type */
108
- export declare const isSymbol: (x: any) => boolean;
109
- /**
110
- * Generates a unique ID using random numbers.
111
- * If prefix is given, the ID is appended to it
112
- */
113
- export declare const uniqueId: (pre?: string) => any;
114
- /**
115
- * Checks if `obj.key` is a function, and calls it with any `args`.
116
- *
117
- *
118
- * @param {*} obj
119
- * @param {PropertyKey} key
120
- * @param {...any[]} args
121
- * @return `obj.key(...args)`
122
- */
123
- export declare function call(obj: any, key: PropertyKey, ...args: any[]): any;
124
- /** Convert number to unicode character */
125
- export declare const chr: (x: number) => string;
126
- /** Convert character to Unicode code point */
127
- export declare const ord: (x: string) => number;
128
- /** `Object.keys(x)` */
129
- export declare const keys: (x: any) => string[];
130
- /** `Object.values(x)` */
131
- export declare const values: (x: any) => unknown[];
132
- /**
133
- * Round `x` to the number of digits after the decimal point. If `digits` is
134
- * omitted, it returns the nearest integer to x.
135
- *
136
- * @param {number} x
137
- * @param {number} [digits=0]
138
- */
139
- export declare function round(x: number, digits?: number): number;
140
- export declare const floor: (x: number) => number;
141
- export declare const ceil: (x: number) => number;
142
- /**
143
- * Yields elements like `[index, item]` from an iterable.
144
- *
145
- *
146
- * @template T
147
- * @param {Iterable<T>} iterable
148
- */
149
- export declare function enumerate<T = unknown>(iterable: Iterable<T>): Generator<(number | T)[], void, unknown>;
150
- export declare const has: (obj: any, attr: PropertyKey) => any;
151
- /**
152
- * Check if the attribute is present in the object, or return optional default.
153
- *
154
- *
155
- * @param {*} obj
156
- * @param {PropertyKey} key
157
- * @param {*} [value=undefined]
158
- * @return The property value or default value
159
- */
160
- export declare function get(obj: any, key: PropertyKey | PropertyKey[], value?: any): any;
161
- export declare function del(x: any, attr: any): any;
162
- export declare function set(self: any, attr: PropertyKey, value: any, writable?: boolean, enumerable?: boolean): any;
163
- export declare const HASH_KEY: unique symbol;
164
- export declare function hash(obj: any): any;
165
- /**
166
- * A hash value generator for strings
167
- *
168
- * @param {string} str
169
- * @return {number}
170
- * @see http://isthe.com/chongo/tech/comp/fnv/
171
- */
172
- export declare function hashCode(str: string): number;
173
- export declare const bin: (n: number) => string;
174
- export declare const hex: (n: number) => string;
175
- export declare const oct: (n: number) => string;
176
- export declare const float: (x: any) => number;
177
- export declare const int: (x: any, base?: number) => number;
178
- export declare const list: (arr?: any) => unknown[];
179
- export declare const next: (iter: Iterator<unknown>) => any;
package/src/globals.js DELETED
@@ -1,309 +0,0 @@
1
- export const True = () => true
2
- export const False = () => false
3
- /**
4
- * A custom error class that inherits from the Error object.
5
- *
6
- *
7
- * @class CustomError
8
- * @extends {Error}
9
- */
10
- export class CustomError extends Error {
11
- /**
12
- * Returns a new CustomError with the specified message.
13
- * @param {string} message
14
- * @constructor
15
- */
16
- constructor(message) {
17
- super(message)
18
- this.name = this.constructor.name
19
- if (typeof Error.captureStackTrace === 'function') {
20
- Error.captureStackTrace(this, this.constructor)
21
- } else {
22
- this.stack = new Error(message).stack
23
- }
24
- }
25
- }
26
- /**
27
- * Custom error to signal an invalid index access.
28
- * @extends {CustomError}
29
- */
30
- export class IndexError extends CustomError {}
31
- /**
32
- * Raised when a system function returns an I/O failure such as "file not found"
33
- * or "disk full".
34
- * @extends {CustomError}
35
- */
36
- export class IOError extends CustomError {}
37
- /**
38
- * Custom error to signal an invalid key access.
39
- * @extends {CustomError}
40
- */
41
- export class KeyError extends CustomError {}
42
- /**
43
- * Custom error to signal an invalid operation.
44
- * @extends {CustomError}
45
- */
46
- export class NotImplementedError extends CustomError {}
47
- /**
48
- * Custom error to signal an invalid value.
49
- * @extends {CustomError}
50
- */
51
- export class ValueError extends CustomError {}
52
- /**
53
- * Raised when the second argument of a division or modulo operation is zero.
54
- * @extends {CustomError}
55
- */
56
- export class ZeroDivisionError extends CustomError {}
57
- /**
58
- * Returns the true type of any value with correct detection for null, Array,
59
- * Object, Promise, Symbol, and NaN.
60
- *
61
- *
62
- * @param {*} value
63
- * @return
64
- */
65
- export function type(value) {
66
- const result = typeof value
67
- if (result === 'object') {
68
- if (value) {
69
- if (value instanceof String) return 'string'
70
- if (value instanceof Boolean) return 'boolean'
71
- if (value instanceof Function) return 'function'
72
- // IE improperly marshals typeof across execution contexts, but a
73
- // cross-context object will still return false for "instanceof Object".
74
- if (value instanceof Array) return 'array'
75
- const className = str(value)
76
- // In Firefox 3.6, attempting to access iframe window objects' length
77
- // property throws an NS_ERROR_FAILURE, so we need to special-case it
78
- // here.
79
- if (className === '[object Window]') return 'object'
80
- // We cannot always use constructor === Array or instanceof Array because
81
- // different frames have different Array objects.
82
- // Mark Miller noticed that Object.prototype.toString
83
- // allows access to the unforgeable [[Class]] property.
84
- // 15.2.4.2 Object.prototype.toString ( )
85
- // When the toString method is called, the following steps are taken:
86
- // 1. Get the [[Class]] property of this object.
87
- // 2. Compute a string value by concatenating the three strings
88
- // "[object ", Result(1), and "]".
89
- // 3. Return Result(2).
90
- // and this behavior survives the destruction of the execution context.
91
- if (className.endsWith('Array]') || Array.isArray(value)) {
92
- return 'array'
93
- }
94
- // HACK: There is still an array case that fails.
95
- // function ArrayImpostor() {}
96
- // ArrayImpostor.prototype = [];
97
- // var impostor = new ArrayImpostor;
98
- // this can be fixed by getting rid of the fast path
99
- // (value instanceof Array) and solely relying on
100
- // (value && Object.prototype.toString.vall(value) === '[object Array]')
101
- // but that would require many more function calls and is not warranted
102
- // unless closure code is receiving objects from untrusted sources.
103
- // IE in cross-window calls does not correctly marshal the function type
104
- // (it appears just as an object) so we cannot use just typeof val ==
105
- // 'function'. However, if the object has a call property, it is a
106
- // function.
107
- if (className.endsWith('Function]') || typeof value.call === 'function') {
108
- return 'function'
109
- }
110
- if (className === '[object Promise]' || value instanceof Promise) {
111
- return 'promise'
112
- }
113
- if (className === '[object Symbol]') {
114
- return 'symbol'
115
- }
116
- } else {
117
- return 'null'
118
- }
119
- } else if (result === 'function' && typeof value.call === 'undefined') {
120
- // In Safari typeof nodeList returns 'function', and on Firefox typeof
121
- // behaves similarly for HTML{Applet,Embed,Object}, Elements and RegExps. We
122
- // would like to return object for those and we can detect an invalid
123
- // function by making sure that the function object has a call method.
124
- return 'object'
125
- } else if (Number.isNaN(value)) return 'NaN'
126
- return result
127
- }
128
- /** Same as `x.toString()`. Returns `''` when x is null or undefined */
129
- export const str = (x) => (x != null ? x.toString() : '')
130
- /** Check if value is a boolean type */
131
- export const isBool = (x) => type(x) === 'boolean'
132
- /** Check if value is an object type */
133
- export const isObject = (x) => typeof x === 'object' && type(x) === 'object'
134
- /** Check if value is a string type */
135
- export const isString = (x) => type(x) === 'string'
136
- /** Check if value is an Array type */
137
- export const isArray = (x) => type(x) === 'array'
138
- /** Check if value is Array-like type.
139
- * A value is considered array-like if it's not a function and has a
140
- * `.length` number property.
141
- */
142
- export const isArrayLike = (x) => {
143
- const T = type(x)
144
- return T === 'array' || (T === 'object' && isNumber(x.length))
145
- }
146
- /** Check if value is a function type */
147
- export const isFunc = (x) => x?.constructor === Function
148
- /** Check if value is a number type */
149
- export const isNumber = (x) => type(x) === 'number'
150
- /** Check if value is a Bigint type */
151
- export const isBigint = (x) => type(x) === 'bigint'
152
- /** Check if value is NaN based on `Number.isNaN` */
153
- export const isNaN = (x) => Number.isNaN(x)
154
- /** Check if value is a Promise type */
155
- export const isPromise = (x) => type(x) === 'promise'
156
- /** Check if value is an async function type */
157
- export const isAsync = (x) => get(x, 'constructor.name') === 'AsyncFunction'
158
- /** Check if value is a generator function type */
159
- export const isGenerator = (x) => {
160
- return get(x, 'constructor.constructor.name') === 'GeneratorFunction'
161
- }
162
- /** Check if value is null or undefined */
163
- export const isNull = (x) => x == null
164
- /** Check if value is not null or undefined */
165
- export const notNull = (x) => x != null
166
- export function len(x) {
167
- if (x == null) return
168
- if (x.length !== undefined) {
169
- return x.length
170
- }
171
- if (isFunc(x.size)) {
172
- return x.size()
173
- }
174
- if (isObject(x)) {
175
- return Object.keys(x).length
176
- }
177
- }
178
- /** Returns true for objects without length or falsey values. */
179
- export const isEmpty = (x) => (len(x) === 0 ? true : !x)
180
- /** Check if value is a Symbol type */
181
- export const isSymbol = (x) => type(x) === 'symbol'
182
- /**
183
- * Generates a unique ID using random numbers.
184
- * If prefix is given, the ID is appended to it
185
- */
186
- export const uniqueId = (pre = '') =>
187
- // @ts-expect-error
188
- (pre || 0) + ((Math.random() * 1e10) >>> 0)
189
- /**
190
- * Checks if `obj.key` is a function, and calls it with any `args`.
191
- *
192
- *
193
- * @param {*} obj
194
- * @param {PropertyKey} key
195
- * @param {...any[]} args
196
- * @return `obj.key(...args)`
197
- */
198
- export function call(obj, key, ...args) {
199
- if (isFunc(get(obj, key))) {
200
- return obj[key](...args)
201
- }
202
- }
203
- /** Convert number to unicode character */
204
- export const chr = (x) => String.fromCodePoint(x)
205
- /** Convert character to Unicode code point */
206
- export const ord = (x) => x.charCodeAt(0)
207
- /** `Object.keys(x)` */
208
- export const keys = (x) => Object.keys(x)
209
- /** `Object.values(x)` */
210
- export const values = (x) => Object.values(x)
211
- /**
212
- * Round `x` to the number of digits after the decimal point. If `digits` is
213
- * omitted, it returns the nearest integer to x.
214
- *
215
- * @param {number} x
216
- * @param {number} [digits=0]
217
- */
218
- export function round(x, digits = 0) {
219
- const base = 10 ** digits
220
- return Math.round(x * base) / base
221
- }
222
- export const floor = (x) => Math.floor(x)
223
- export const ceil = (x) => Math.ceil(x)
224
- /**
225
- * Yields elements like `[index, item]` from an iterable.
226
- *
227
- *
228
- * @template T
229
- * @param {Iterable<T>} iterable
230
- */
231
- export function* enumerate(iterable) {
232
- let i = 0
233
- for (const item of iterable) {
234
- yield [i++, item]
235
- }
236
- }
237
- export const has = (obj, attr) => obj && attr in obj
238
- /**
239
- * Check if the attribute is present in the object, or return optional default.
240
- *
241
- *
242
- * @param {*} obj
243
- * @param {PropertyKey} key
244
- * @param {*} [value=undefined]
245
- * @return The property value or default value
246
- */
247
- export function get(obj, key, value = undefined) {
248
- if (obj == null) return value
249
- let paths = Array.isArray(key) ? key : [key]
250
- if (typeof key === 'string') {
251
- paths = key.split('.')
252
- }
253
- try {
254
- let result = obj
255
- for (const k of paths) {
256
- result = result[k]
257
- }
258
- return result === undefined ? value : result
259
- } catch (error) {
260
- return value
261
- }
262
- }
263
- export function del(x, attr) {
264
- if (x != null) delete x[attr]
265
- return x
266
- }
267
- export function set(self, attr, value, writable = false, enumerable = false) {
268
- return Object.defineProperty(self, attr, {
269
- value,
270
- enumerable,
271
- writable
272
- })
273
- }
274
- export const HASH_KEY = Symbol.for('HASH_KEY')
275
- export function hash(obj) {
276
- if (typeof obj === 'string') {
277
- return hashCode(obj)
278
- }
279
- if (typeof obj === 'object') {
280
- if (obj[HASH_KEY] == null) {
281
- set(obj, HASH_KEY, uniqueId())
282
- }
283
- return obj[HASH_KEY]
284
- }
285
- return obj
286
- }
287
- /**
288
- * A hash value generator for strings
289
- *
290
- * @param {string} str
291
- * @return {number}
292
- * @see http://isthe.com/chongo/tech/comp/fnv/
293
- */
294
- export function hashCode(str) {
295
- const FNV1_32A_INIT = 0x811c9dc5
296
- let hval = FNV1_32A_INIT
297
- for (let i = 0; i < str.length; ++i) {
298
- hval ^= str.charCodeAt(i)
299
- hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24)
300
- }
301
- return hval >>> 0
302
- }
303
- export const bin = (n) => n.toString(2)
304
- export const hex = (n) => n.toString(16)
305
- export const oct = (n) => n.toString(8)
306
- export const float = (x) => parseFloat(x)
307
- export const int = (x, base = 10) => parseInt(x, base)
308
- export const list = (arr) => (arr ? Array.from(arr) : [])
309
- export const next = (iter) => iter.next().value