atomic-fns 0.1.0 → 0.2.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.
package/src/functools.ts CHANGED
@@ -20,7 +20,7 @@ export const compose = (...args) => flow(args.reverse())
20
20
  /**
21
21
  * 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.
22
22
  *
23
- * @export
23
+ *
24
24
  * @param {Function} func The function to have its output memoized.
25
25
  * @param {Function} [resolver] The function to resolve the cache key.
26
26
  * @return {Function} Returns the new memoized function.
@@ -40,7 +40,7 @@ export function memoize(func: Function, resolver?: Function): Function {
40
40
  /**
41
41
  * 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.
42
42
  *
43
- * @export
43
+ *
44
44
  * @param {Function} func The function to debounce.
45
45
  * @param {number} wait The number of milliseconds to delay.
46
46
  * @param {{ maxWait: number }} { maxWait } The maximum time `func` is allowed to be delayed before it's invoked.
@@ -71,7 +71,7 @@ export function debounce(func: Function, wait: number, { maxWait }: { maxWait: n
71
71
  /**
72
72
  * 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.
73
73
  *
74
- * @export
74
+ *
75
75
  * @param {Function} func The function to throttle.
76
76
  * @param {number} time The number of milliseconds to throttle invocations to.
77
77
  * @return {Function} Returns the new throttled function.
package/src/globals.d.ts CHANGED
@@ -1,5 +1,175 @@
1
- interface ErrorConstructor {
2
- /** See https://v8.dev/docs/stack-trace-api#stack-trace-collection-for-custom-exceptions. */
3
- // eslint-disable-next-line @typescript-eslint/ban-types
4
- captureStackTrace(error: Object, constructor?: Function): void
1
+ export declare type Comp = (x: any, y: any) => number;
2
+ export declare type Function = (...args: any[]) => any;
3
+ export declare type Iteratee = (value: any, key?: any, arr?: any) => any;
4
+ export declare const True: () => boolean;
5
+ export declare const False: () => boolean;
6
+ /**
7
+ * A custom error class that inherits from the Error object.
8
+ *
9
+ *
10
+ * @class CustomError
11
+ * @extends {Error}
12
+ */
13
+ export declare class CustomError extends Error {
14
+ /**
15
+ * Returns a new CustomError with the specified message.
16
+ * @param message
17
+ * @constructor
18
+ */
19
+ constructor(message?: any);
5
20
  }
21
+ /**
22
+ * Custom error to signal an invalid index access.
23
+ * @extends {CustomError}
24
+ */
25
+ export declare class IndexError extends CustomError {
26
+ }
27
+ /**
28
+ * Raised when a system function returns an I/O failure such as "file not found"
29
+ * or "disk full".
30
+ * @extends {CustomError}
31
+ */
32
+ export declare class IOError extends CustomError {
33
+ }
34
+ /**
35
+ * Custom error to signal an invalid key access.
36
+ * @extends {CustomError}
37
+ */
38
+ export declare class KeyError extends CustomError {
39
+ }
40
+ /**
41
+ * Custom error to signal an invalid operation.
42
+ * @extends {CustomError}
43
+ */
44
+ export declare class NotImplementedError extends CustomError {
45
+ }
46
+ /**
47
+ * Custom error to signal an invalid value.
48
+ * @extends {CustomError}
49
+ */
50
+ export declare class ValueError extends CustomError {
51
+ }
52
+ /**
53
+ * Raised when the second argument of a division or modulo operation is zero.
54
+ * @extends {CustomError}
55
+ */
56
+ export declare class ZeroDivisionError extends CustomError {
57
+ }
58
+ /**
59
+ * Returns the true type of any value with correct detection for null, Array,
60
+ * Object, Promise, Symbol, and NaN.
61
+ *
62
+ *
63
+ * @param {*} value
64
+ * @return
65
+ */
66
+ export declare function type(value: any): "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" | "array" | "promise" | "null" | "NaN";
67
+ /** Same as `x.toString()`. Returns `''` when x is null or undefined */
68
+ export declare const str: (x: any) => any;
69
+ /** Check if value is a boolean type */
70
+ export declare const isBool: (x: any) => boolean;
71
+ /** Check if value is an object type */
72
+ export declare const isObject: (x: any) => boolean;
73
+ /** Check if value is a string type */
74
+ export declare const isString: (x: any) => boolean;
75
+ /** Check if value is an Array type */
76
+ export declare const isArray: (x: any) => boolean;
77
+ /** Check if value is Array-like type.
78
+ * A value is considered array-like if it's not a function and has a
79
+ * `.length` number property.
80
+ */
81
+ export declare const isArrayLike: (x: any) => boolean;
82
+ /** Check if value is a function type */
83
+ export declare const isFunc: (x: any) => boolean;
84
+ /** Check if value is a number type */
85
+ export declare const isNumber: (x: any) => boolean;
86
+ /** Check if value is a Bigint type */
87
+ export declare const isBigint: (x: any) => boolean;
88
+ /** Check if value is NaN based on `Number.isNaN` */
89
+ export declare const isNaN: (x: any) => boolean;
90
+ /** Check if value is a Promise type */
91
+ export declare const isPromise: (x: any) => boolean;
92
+ /** Check if value is an async function type */
93
+ export declare const isAsync: (x: any) => boolean;
94
+ /** Check if value is a generator function type */
95
+ export declare const isGenerator: (x: any) => boolean;
96
+ /** Check if value is null or undefined */
97
+ export declare const isNull: (x: any) => boolean;
98
+ /** Check if value is not null or undefined */
99
+ export declare const notNull: (x: any) => boolean;
100
+ export declare function len(x: any): any;
101
+ /** Returns true for objects without length or falsey values. */
102
+ export declare const isEmpty: (x: any) => boolean;
103
+ /** Check if value is a Symbol type */
104
+ export declare const isSymbol: (x: any) => boolean;
105
+ /**
106
+ * Generates a unique ID using random numbers.
107
+ * If prefix is given, the ID is appended to it
108
+ */
109
+ export declare const uniqueId: (pre?: string) => any;
110
+ /**
111
+ * Checks if `obj.key` is a function, and calls it with any `args`.
112
+ *
113
+ *
114
+ * @param {*} obj
115
+ * @param {PropertyKey} key
116
+ * @param {...any[]} args
117
+ * @return `obj.key(...args)`
118
+ */
119
+ export declare function call(obj: any, key: PropertyKey, ...args: any[]): any;
120
+ /** Convert number to unicode character */
121
+ export declare const chr: (x: number) => string;
122
+ /** Convert character to Unicode code point */
123
+ export declare const ord: (x: string) => number;
124
+ /** `Object.keys(x)` */
125
+ export declare const keys: (x: any) => string[];
126
+ /** `Object.values(x)` */
127
+ export declare const values: (x: any) => unknown[];
128
+ /**
129
+ * Round `x` to the number of digits after the decimal point. If `digits` is
130
+ * omitted, it returns the nearest integer to x.
131
+ *
132
+ * @param {number} x
133
+ * @param {number} [digits=0]
134
+ */
135
+ export declare function round(x: number, digits?: number): number;
136
+ export declare const floor: (x: number) => number;
137
+ export declare const ceil: (x: number) => number;
138
+ /**
139
+ * Yields elements like [index, item] from an iterable.
140
+ *
141
+ *
142
+ * @template T
143
+ * @param {Iterable<T>} iterable
144
+ */
145
+ export declare function enumerate<T = unknown>(iterable: Iterable<T>): Generator<(number | T)[], void, unknown>;
146
+ export declare const has: (obj: any, attr: PropertyKey) => any;
147
+ /**
148
+ * Check if the attribute is present in the object, or return optional default.
149
+ *
150
+ *
151
+ * @param {*} obj
152
+ * @param {PropertyKey} key
153
+ * @param {*} [value=undefined]
154
+ * @return The property value or default value
155
+ */
156
+ export declare function get(obj: any, key: PropertyKey | PropertyKey[], value?: any): any;
157
+ export declare function del(x: any, attr: any): any;
158
+ export declare function set(self: any, attr: PropertyKey, value: any, writable?: boolean, enumerable?: boolean): any;
159
+ export declare const HASH_KEY: unique symbol;
160
+ export declare function hash(obj: any): any;
161
+ /**
162
+ * A hash value generator for strings
163
+ *
164
+ * @param {string} str
165
+ * @return {number}
166
+ * @see http://isthe.com/chongo/tech/comp/fnv/
167
+ */
168
+ export declare function hashCode(str: string): number;
169
+ export declare const bin: (n: number) => string;
170
+ export declare const hex: (n: number) => string;
171
+ export declare const oct: (n: number) => string;
172
+ export declare const float: (x: any) => number;
173
+ export declare const int: (x: any, base?: number) => number;
174
+ export declare const list: (arr?: any) => unknown[];
175
+ export declare const next: (iter: Iterator<unknown>) => any;
@@ -3,7 +3,7 @@ export const False = () => false;
3
3
  /**
4
4
  * A custom error class that inherits from the Error object.
5
5
  *
6
- * @export
6
+ *
7
7
  * @class CustomError
8
8
  * @extends {Error}
9
9
  */
@@ -65,7 +65,7 @@ export class ZeroDivisionError extends CustomError {
65
65
  * Returns the true type of any value with correct detection for null, Array,
66
66
  * Object, Promise, Symbol, and NaN.
67
67
  *
68
- * @export
68
+ *
69
69
  * @param {*} value
70
70
  * @return
71
71
  */
@@ -141,12 +141,8 @@ export function type(value) {
141
141
  return 'NaN';
142
142
  return result;
143
143
  }
144
- /** Same as calling toString() */
145
- export const str = (x) => {
146
- if (isNull(x))
147
- return '';
148
- return x.toString?.() ?? String(x);
149
- };
144
+ /** Same as `x.toString()`. Returns `''` when x is null or undefined */
145
+ export const str = (x) => (x != null ? x.toString() : '');
150
146
  /** Check if value is a boolean type */
151
147
  export const isBool = (x) => type(x) === 'boolean';
152
148
  /** Check if value is an object type */
@@ -174,20 +170,22 @@ export const isNaN = (x) => Number.isNaN(x);
174
170
  /** Check if value is a Promise type */
175
171
  export const isPromise = (x) => type(x) === 'promise';
176
172
  /** Check if value is an async function type */
177
- export const isAsync = (x) => x?.constructor.name === 'AsyncFunction';
173
+ export const isAsync = (x) => get(x, 'constructor.name') === 'AsyncFunction';
178
174
  /** Check if value is a generator function type */
179
175
  export const isGenerator = (x) => {
180
- return x?.constructor.constructor?.name === 'GeneratorFunction';
176
+ return get(x, 'constructor.constructor.name') === 'GeneratorFunction';
181
177
  };
182
178
  /** Check if value is null or undefined */
183
179
  export const isNull = (x) => x == null;
184
180
  /** Check if value is not null or undefined */
185
181
  export const notNull = (x) => x != null;
186
182
  export function len(x) {
187
- if (isNumber(x?.length)) {
183
+ if (x == null)
184
+ return;
185
+ if (x.length !== undefined) {
188
186
  return x.length;
189
187
  }
190
- if (isFunc(x?.size)) {
188
+ if (isFunc(x.size)) {
191
189
  return x.size();
192
190
  }
193
191
  if (isObject(x)) {
@@ -208,7 +206,7 @@ export const uniqueId = (pre = '') =>
208
206
  /**
209
207
  * Checks if `obj.key` is a function, and calls it with any `args`.
210
208
  *
211
- * @export
209
+ *
212
210
  * @param {*} obj
213
211
  * @param {PropertyKey} key
214
212
  * @param {...any[]} args
@@ -230,7 +228,7 @@ export const values = (x) => Object.values(x);
230
228
  /**
231
229
  * Round `x` to the number of digits after the decimal point. If `digits` is
232
230
  * omitted, it returns the nearest integer to x.
233
- * @export
231
+ *
234
232
  * @param {number} x
235
233
  * @param {number} [digits=0]
236
234
  */
@@ -243,7 +241,7 @@ export const ceil = (x) => Math.ceil(x);
243
241
  /**
244
242
  * Yields elements like [index, item] from an iterable.
245
243
  *
246
- * @export
244
+ *
247
245
  * @template T
248
246
  * @param {Iterable<T>} iterable
249
247
  */
@@ -257,16 +255,15 @@ export const has = (obj, attr) => obj && attr in obj;
257
255
  /**
258
256
  * Check if the attribute is present in the object, or return optional default.
259
257
  *
260
- * @export
258
+ *
261
259
  * @param {*} obj
262
260
  * @param {PropertyKey} key
263
261
  * @param {*} [value=undefined]
264
262
  * @return The property value or default value
265
263
  */
266
264
  export function get(obj, key, value = undefined) {
267
- if (obj == null) {
268
- return value ?? obj;
269
- }
265
+ if (obj == null)
266
+ return value;
270
267
  let paths = Array.isArray(key) ? key : [key];
271
268
  if (typeof key === 'string') {
272
269
  paths = key.split('.');
@@ -276,7 +273,7 @@ export function get(obj, key, value = undefined) {
276
273
  for (const k of paths) {
277
274
  result = result[k];
278
275
  }
279
- return result ?? value;
276
+ return result === undefined ? value : result;
280
277
  }
281
278
  catch (error) {
282
279
  return value;
@@ -309,7 +306,7 @@ export function hash(obj) {
309
306
  }
310
307
  /**
311
308
  * A hash value generator for strings
312
- * @export
309
+ *
313
310
  * @param {string} str
314
311
  * @return {number}
315
312
  * @see http://isthe.com/chongo/tech/comp/fnv/
package/src/globals.ts CHANGED
@@ -11,7 +11,7 @@ export const False = () => false
11
11
  /**
12
12
  * A custom error class that inherits from the Error object.
13
13
  *
14
- * @export
14
+ *
15
15
  * @class CustomError
16
16
  * @extends {Error}
17
17
  */
@@ -73,7 +73,7 @@ export class ZeroDivisionError extends CustomError {}
73
73
  * Returns the true type of any value with correct detection for null, Array,
74
74
  * Object, Promise, Symbol, and NaN.
75
75
  *
76
- * @export
76
+ *
77
77
  * @param {*} value
78
78
  * @return
79
79
  */
@@ -144,11 +144,8 @@ export function type(value) {
144
144
  return result
145
145
  }
146
146
 
147
- /** Same as calling toString() */
148
- export const str = (x): string => {
149
- if (isNull(x)) return ''
150
- return x.toString?.() ?? String(x)
151
- }
147
+ /** Same as `x.toString()`. Returns `''` when x is null or undefined */
148
+ export const str = (x) => (x != null ? x.toString() : '')
152
149
 
153
150
  /** Check if value is a boolean type */
154
151
  export const isBool = (x) => type(x) === 'boolean'
@@ -187,11 +184,11 @@ export const isNaN = (x) => Number.isNaN(x)
187
184
  export const isPromise = (x) => type(x) === 'promise'
188
185
 
189
186
  /** Check if value is an async function type */
190
- export const isAsync = (x) => x?.constructor.name === 'AsyncFunction'
187
+ export const isAsync = (x) => get(x, 'constructor.name') === 'AsyncFunction'
191
188
 
192
189
  /** Check if value is a generator function type */
193
190
  export const isGenerator = (x) => {
194
- return x?.constructor.constructor?.name === 'GeneratorFunction'
191
+ return get(x, 'constructor.constructor.name') === 'GeneratorFunction'
195
192
  }
196
193
 
197
194
  /** Check if value is null or undefined */
@@ -201,10 +198,11 @@ export const isNull = (x) => x == null
201
198
  export const notNull = (x) => x != null
202
199
 
203
200
  export function len(x) {
204
- if (isNumber(x?.length)) {
201
+ if (x == null) return
202
+ if (x.length !== undefined) {
205
203
  return x.length
206
204
  }
207
- if (isFunc(x?.size)) {
205
+ if (isFunc(x.size)) {
208
206
  return x.size()
209
207
  }
210
208
  if (isObject(x)) {
@@ -229,7 +227,7 @@ export const uniqueId = (pre: string = '') =>
229
227
  /**
230
228
  * Checks if `obj.key` is a function, and calls it with any `args`.
231
229
  *
232
- * @export
230
+ *
233
231
  * @param {*} obj
234
232
  * @param {PropertyKey} key
235
233
  * @param {...any[]} args
@@ -256,7 +254,7 @@ export const values = (x) => Object.values(x)
256
254
  /**
257
255
  * Round `x` to the number of digits after the decimal point. If `digits` is
258
256
  * omitted, it returns the nearest integer to x.
259
- * @export
257
+ *
260
258
  * @param {number} x
261
259
  * @param {number} [digits=0]
262
260
  */
@@ -272,7 +270,7 @@ export const ceil = (x: number) => Math.ceil(x)
272
270
  /**
273
271
  * Yields elements like [index, item] from an iterable.
274
272
  *
275
- * @export
273
+ *
276
274
  * @template T
277
275
  * @param {Iterable<T>} iterable
278
276
  */
@@ -288,16 +286,14 @@ export const has = (obj, attr: PropertyKey) => obj && attr in obj
288
286
  /**
289
287
  * Check if the attribute is present in the object, or return optional default.
290
288
  *
291
- * @export
289
+ *
292
290
  * @param {*} obj
293
291
  * @param {PropertyKey} key
294
292
  * @param {*} [value=undefined]
295
293
  * @return The property value or default value
296
294
  */
297
295
  export function get(obj: any, key: PropertyKey | PropertyKey[], value: any = undefined) {
298
- if (obj == null) {
299
- return value ?? obj
300
- }
296
+ if (obj == null) return value
301
297
 
302
298
  let paths = Array.isArray(key) ? key : [key]
303
299
  if (typeof key === 'string') {
@@ -309,7 +305,7 @@ export function get(obj: any, key: PropertyKey | PropertyKey[], value: any = und
309
305
  for (const k of paths) {
310
306
  result = result[k]
311
307
  }
312
- return result ?? value
308
+ return result === undefined ? value : result
313
309
  } catch (error) {
314
310
  return value
315
311
  }
@@ -347,7 +343,7 @@ export function hash(obj) {
347
343
 
348
344
  /**
349
345
  * A hash value generator for strings
350
- * @export
346
+ *
351
347
  * @param {string} str
352
348
  * @return {number}
353
349
  * @see http://isthe.com/chongo/tech/comp/fnv/
File without changes
File without changes
File without changes
@@ -35,7 +35,7 @@ export function reversed(iterable) {
35
35
  *
36
36
  * If `args` is an Object, returns the sorted keys.
37
37
  *
38
- * @export
38
+ *
39
39
  * @param {(Array | Object)} args
40
40
  * @param {(boolean | Function)} [key]
41
41
  * @param {(boolean | Comp)} [reverse]
@@ -56,7 +56,7 @@ export function sorted(args, key, reverse, compareFn) {
56
56
  key = id;
57
57
  }
58
58
  const copy = Array.from(args);
59
- const _compare = compKey(compareFn ?? comp, key ?? id);
59
+ const _compare = compKey(compareFn || comp, key || id);
60
60
  copy.sort(_compare);
61
61
  if (reverse)
62
62
  copy.reverse();
@@ -67,19 +67,18 @@ export function sorted(args, key, reverse, compareFn) {
67
67
  * - sort([...], true) => reverse order
68
68
  * - sort([...], (x, y) => number) => using custom compare
69
69
  * - sort([...], true, (x, y) => number) => reverse and using custom compare
70
- * @export
70
+ *
71
71
  * @param {any[]} args
72
72
  * @param {(boolean | Comp)} [reverse]
73
73
  * @param {Comp} [compareFn]
74
74
  * @return
75
75
  */
76
76
  export function sort(args, reverse, compareFn) {
77
- compareFn ??= comp;
78
77
  if (typeof reverse === 'function') {
79
78
  compareFn = reverse;
80
79
  reverse = false;
81
80
  }
82
- args.sort(compareFn);
81
+ args.sort(compareFn || comp);
83
82
  if (reverse === true)
84
83
  args.reverse();
85
84
  return args;
package/src/itertools.ts CHANGED
@@ -43,7 +43,7 @@ export function sorted(args: any[], key: Function, reverse: boolean): any[]
43
43
  *
44
44
  * If `args` is an Object, returns the sorted keys.
45
45
  *
46
- * @export
46
+ *
47
47
  * @param {(Array | Object)} args
48
48
  * @param {(boolean | Function)} [key]
49
49
  * @param {(boolean | Comp)} [reverse]
@@ -62,7 +62,7 @@ export function sorted(args, key?: boolean | Function, reverse?: boolean | Comp,
62
62
  key = id
63
63
  }
64
64
  const copy = Array.from(args)
65
- const _compare = compKey(compareFn ?? comp, key ?? id)
65
+ const _compare = compKey(compareFn || comp, key || id)
66
66
  copy.sort(_compare)
67
67
  if (reverse) copy.reverse()
68
68
  return copy
@@ -78,19 +78,18 @@ export function sort(args: any[], reverse: boolean, compareFn: Comp): any[]
78
78
  * - sort([...], true) => reverse order
79
79
  * - sort([...], (x, y) => number) => using custom compare
80
80
  * - sort([...], true, (x, y) => number) => reverse and using custom compare
81
- * @export
81
+ *
82
82
  * @param {any[]} args
83
83
  * @param {(boolean | Comp)} [reverse]
84
84
  * @param {Comp} [compareFn]
85
85
  * @return
86
86
  */
87
87
  export function sort(args: any[], reverse?: boolean | Comp, compareFn?: Comp) {
88
- compareFn ??= comp
89
88
  if (typeof reverse === 'function') {
90
89
  compareFn = reverse
91
90
  reverse = false
92
91
  }
93
- args.sort(compareFn)
92
+ args.sort(compareFn || comp)
94
93
  if (reverse === true) args.reverse()
95
94
  return args
96
95
  }
@@ -1,7 +1,7 @@
1
1
  export declare function abs(x: number): any;
2
2
  /**
3
3
  * Returns a tuple like (x / y, x % y)
4
- * @export
4
+ *
5
5
  * @param {number} x
6
6
  * @param {number} y
7
7
  * @return {number[]}
@@ -8,7 +8,7 @@ export function abs(x) {
8
8
  }
9
9
  /**
10
10
  * Returns a tuple like (x / y, x % y)
11
- * @export
11
+ *
12
12
  * @param {number} x
13
13
  * @param {number} y
14
14
  * @return {number[]}
package/src/math.ts CHANGED
@@ -9,7 +9,7 @@ export function abs(x: number) {
9
9
 
10
10
  /**
11
11
  * Returns a tuple like (x / y, x % y)
12
- * @export
12
+ *
13
13
  * @param {number} x
14
14
  * @param {number} y
15
15
  * @return {number[]}
File without changes
File without changes
@@ -21,7 +21,7 @@ export declare function mod(x: any, y: any): any;
21
21
  /**
22
22
  * Calculates `x` to the power of `y`. If `x` implements a custom `pow` operator
23
23
  * it will return `x.pow(y)`.
24
- * @export
24
+ *
25
25
  * @param {*} x
26
26
  * @param {*} y
27
27
  * @return `x` raised to the power `y`
@@ -115,7 +115,7 @@ export function mod(x, y) {
115
115
  /**
116
116
  * Calculates `x` to the power of `y`. If `x` implements a custom `pow` operator
117
117
  * it will return `x.pow(y)`.
118
- * @export
118
+ *
119
119
  * @param {*} x
120
120
  * @param {*} y
121
121
  * @return `x` raised to the power `y`
package/src/operators.ts CHANGED
@@ -114,7 +114,7 @@ export function mod(x, y) {
114
114
  /**
115
115
  * Calculates `x` to the power of `y`. If `x` implements a custom `pow` operator
116
116
  * it will return `x.pow(y)`.
117
- * @export
117
+ *
118
118
  * @param {*} x
119
119
  * @param {*} y
120
120
  * @return `x` raised to the power `y`
@@ -0,0 +1,22 @@
1
+ /** Returns a random float between a [min, max) value (max exclusive). */
2
+ export declare const random: (min?: number, max?: number) => number;
3
+ /** Returns a random integer between a [min, max] value (inclusive). */
4
+ export declare const randomInt: (min?: number, max?: number) => number;
5
+ /** Returns the item at some random index in a sequence. */
6
+ export declare const choice: (arr: any[]) => any;
7
+ /**
8
+ * Returns a random sample of size k from a list of items.
9
+ *
10
+ * @export
11
+ * @param {any[]} arr
12
+ * @param {number} k
13
+ * @return
14
+ */
15
+ export declare function sample(arr: any[], k: number): any[] | undefined;
16
+ /**
17
+ * Shuffles a collection elements in-place. Uses the Fisher-Yates algorithm for uniform shuffling. If collection is an Object it returns shuffled `Object.values()`.
18
+ *
19
+ * @param {*} arr
20
+ * @return
21
+ */
22
+ export declare function shuffle(arr: any): any;
package/src/random.js ADDED
@@ -0,0 +1,48 @@
1
+ import { isObject } from './globals';
2
+ /** Returns a random float between a [min, max) value (max exclusive). */
3
+ export const random = (min = 0, max = 1) => Math.random() * (max - min) + min;
4
+ /** Returns a random integer between a [min, max] value (inclusive). */
5
+ export const randomInt = (min = 0, max = 1) => Math.round(random(min, max));
6
+ /** Returns the item at some random index in a sequence. */
7
+ export const choice = (arr) => {
8
+ if (!arr || !arr.length)
9
+ return;
10
+ return arr[randomInt(0, arr.length - 1)];
11
+ };
12
+ /**
13
+ * Returns a random sample of size k from a list of items.
14
+ *
15
+ * @export
16
+ * @param {any[]} arr
17
+ * @param {number} k
18
+ * @return
19
+ */
20
+ export function sample(arr, k) {
21
+ if (!arr || !arr.length || arr.length < k)
22
+ return;
23
+ const result = [];
24
+ for (let i = 0; i < k; i++) {
25
+ result.push(choice(arr));
26
+ }
27
+ return result;
28
+ }
29
+ /**
30
+ * Shuffles a collection elements in-place. Uses the Fisher-Yates algorithm for uniform shuffling. If collection is an Object it returns shuffled `Object.values()`.
31
+ *
32
+ * @param {*} arr
33
+ * @return
34
+ */
35
+ export function shuffle(arr) {
36
+ if (!arr || !arr.length)
37
+ return;
38
+ if (isObject(arr))
39
+ arr = Object.values(arr);
40
+ const n = arr.length - 1;
41
+ for (let i = n; i > 0; i--) {
42
+ const j = randomInt(0, i);
43
+ const temp = arr[j];
44
+ arr[j] = arr[i];
45
+ arr[i] = temp;
46
+ }
47
+ return arr;
48
+ }