atomic-fns 0.2.0 → 0.2.2

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