@terrygonguet/utils 0.11.0 → 0.12.1

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/dist/async.js DELETED
@@ -1,105 +0,0 @@
1
- // src/async.ts
2
- function pause(ms) {
3
- return new Promise((resolve) => setTimeout(resolve, ms));
4
- }
5
- function retry(providerOrOptions, options) {
6
- if (typeof providerOrOptions == "function")
7
- return _retry(providerOrOptions, options);
8
- else
9
- return (provider) => _retry(provider, providerOrOptions);
10
- }
11
- async function _retry(provider, { count = Infinity, delay } = {}) {
12
- let retryCount = 0;
13
- let lastError;
14
- do {
15
- try {
16
- return await provider();
17
- } catch (error) {
18
- lastError = error;
19
- retryCount++;
20
- switch (typeof delay) {
21
- case "number":
22
- await pause(delay);
23
- break;
24
- case "function":
25
- await pause(delay(retryCount, error));
26
- break;
27
- }
28
- }
29
- } while (retryCount <= count);
30
- throw lastError;
31
- }
32
- function asyncMap(dataOrF, ForOptions, options) {
33
- if (typeof dataOrF == "function" && typeof ForOptions != "function") {
34
- const f = dataOrF;
35
- const options2 = ForOptions;
36
- return (data) => asyncMap_(data, f, options2);
37
- } else if (Array.isArray(dataOrF) && typeof ForOptions == "function") {
38
- const data = dataOrF;
39
- const f = ForOptions;
40
- return asyncMap_(data, f, options);
41
- } else throw new Error("Invalid arguments passed to asyncMap");
42
- }
43
- async function asyncMap_(data, f, {
44
- concurrent = 5,
45
- failFast = false,
46
- withSourceIndexes = false
47
- } = {}) {
48
- return new Promise((resolve, reject) => {
49
- const resolved = [];
50
- const errors = [];
51
- const inFlight = /* @__PURE__ */ new Map();
52
- let next = 0;
53
- let stop = false;
54
- function queue(i) {
55
- if (!stop && i > 0 && inFlight.size == 0) return finish();
56
- if (stop || i >= data.length) return;
57
- inFlight.set(
58
- i,
59
- f(data[i], i, data).then(
60
- (result) => void resolved.push([i, result]),
61
- (error) => {
62
- if (!failFast) errors.push([i, error]);
63
- else {
64
- stop = true;
65
- reject(error);
66
- }
67
- }
68
- ).finally(() => {
69
- inFlight.delete(i);
70
- queue(next);
71
- })
72
- );
73
- next++;
74
- }
75
- function finish() {
76
- resolved.sort(([a], [b]) => a - b);
77
- if (failFast) {
78
- if (withSourceIndexes) resolve(resolved);
79
- else resolve(resolved.map(([, value]) => value));
80
- } else {
81
- errors.sort(([a], [b]) => a - b);
82
- if (withSourceIndexes)
83
- resolve({
84
- results: resolved,
85
- errors
86
- });
87
- else
88
- resolve({
89
- results: resolved.map(([, value]) => value),
90
- errors: errors.map(([, error]) => error)
91
- });
92
- }
93
- }
94
- if (data.length == 0) finish();
95
- else
96
- for (let i = 0; i < concurrent; i++) {
97
- queue(next);
98
- }
99
- });
100
- }
101
- export {
102
- asyncMap,
103
- pause,
104
- retry
105
- };
package/dist/index.js DELETED
@@ -1,85 +0,0 @@
1
- // src/index.ts
2
- function clamp(value, min, max) {
3
- return Math.min(Math.max(value, min), max);
4
- }
5
- function createNoopProxy() {
6
- const noop2 = () => proxy;
7
- const no = () => false;
8
- const yes = () => true;
9
- const proxy = new Proxy(() => {
10
- }, {
11
- get: noop2,
12
- set: noop2,
13
- apply: noop2,
14
- construct: noop2,
15
- deleteProperty: yes,
16
- has: yes,
17
- preventExtensions: no,
18
- defineProperty: no
19
- });
20
- return proxy;
21
- }
22
- function noop() {
23
- }
24
- function exhaustive(_) {
25
- throw new Error("This should never be called");
26
- }
27
- async function hash(message) {
28
- const encoder = new TextEncoder();
29
- const data = encoder.encode(message);
30
- const hash2 = await crypto.subtle.digest("SHA-1", data);
31
- return hash2;
32
- }
33
- function* range(start, end, step = 1) {
34
- for (let i = start; i < end; i += step) {
35
- yield i;
36
- }
37
- }
38
- function yesno(value) {
39
- switch (value?.toLowerCase()) {
40
- case "1":
41
- case "y":
42
- case "yes":
43
- case "true":
44
- case "on":
45
- return true;
46
- default:
47
- return false;
48
- }
49
- }
50
- function mapListPush(map, key, value) {
51
- const arr = map.get(key) ?? [];
52
- arr.push(value);
53
- return map.set(key, arr);
54
- }
55
- function recordListPush(record, key, value) {
56
- const arr = record[key] ?? [];
57
- arr.push(value);
58
- record[key] = arr;
59
- return record;
60
- }
61
- function tryCatch(f, ...args) {
62
- try {
63
- const promiseOrResult = f(...args);
64
- if (promiseOrResult instanceof Promise)
65
- return promiseOrResult.then(
66
- (result) => [null, result],
67
- (error) => [error, null]
68
- );
69
- else return [null, promiseOrResult];
70
- } catch (error) {
71
- return [error, null];
72
- }
73
- }
74
- export {
75
- clamp,
76
- createNoopProxy,
77
- exhaustive,
78
- hash,
79
- mapListPush,
80
- noop,
81
- range,
82
- recordListPush,
83
- tryCatch,
84
- yesno
85
- };
package/dist/json.js DELETED
@@ -1,63 +0,0 @@
1
- // src/json.ts
2
- function safeParse(str, defaultValue, reviver) {
3
- try {
4
- return JSON.parse(str, reviver);
5
- } catch (_) {
6
- return defaultValue;
7
- }
8
- }
9
- function schemaParse(schema, str, options) {
10
- try {
11
- const parsed = JSON.parse(str, options?.reviver);
12
- const result = schema["~standard"].validate(parsed);
13
- if (options?.async) {
14
- if (result instanceof Promise) {
15
- return result.then(
16
- (result2) => result2.issues ? [null, result2, null] : [null, null, result2.value],
17
- (err) => [err, null, null]
18
- );
19
- } else {
20
- return Promise.resolve(
21
- result.issues ? [null, result, null] : [null, null, result.value]
22
- );
23
- }
24
- } else {
25
- if (result instanceof Promise)
26
- throw new Error(
27
- "Function schemaParse() whas called with an async schema but without the async flag"
28
- );
29
- else if (result.issues) return [null, result, null];
30
- else return [null, null, result.value];
31
- }
32
- } catch (error) {
33
- return [error, null, null];
34
- }
35
- }
36
- function schemaParseWithDefault(schema, str, defaultValue, options) {
37
- const result = schemaParse(schema, str, options);
38
- if (result instanceof Promise) {
39
- return result.then(([error, failure, value]) => {
40
- if (failure) {
41
- options?.out_validationFailure?.push(failure);
42
- return defaultValue;
43
- } else if (error) {
44
- options?.out_parseError?.push(error);
45
- return defaultValue;
46
- } else return value;
47
- });
48
- } else {
49
- const [error, failure, value] = result;
50
- if (failure) {
51
- options?.out_validationFailure?.push(failure);
52
- return defaultValue;
53
- } else if (error) {
54
- options?.out_parseError?.push(error);
55
- return defaultValue;
56
- } else return value;
57
- }
58
- }
59
- export {
60
- safeParse,
61
- schemaParse,
62
- schemaParseWithDefault
63
- };
package/dist/option.d.ts DELETED
@@ -1,45 +0,0 @@
1
- declare class Option<T> {
2
- #private;
3
- readonly _kind: "Some" | "None";
4
- readonly value: T;
5
- private constructor();
6
- [Symbol.iterator](): Iterator<Option<T>, T>;
7
- static do<T>(f: () => Iterator<Option<any>, T, any>): Option<T>;
8
- static from<T>(maybeValue: unknown, { allowOptionLikePOJO }?: {
9
- allowOptionLikePOJO?: boolean | undefined;
10
- }): Option<T>;
11
- static wrapFunction<T, Args extends any[]>(f: (...args: Args) => T | undefined | null, { allowOptionLikePOJO }?: {
12
- allowOptionLikePOJO?: boolean | undefined;
13
- }): (...args: Args) => Option<T>;
14
- static isOption<T>(maybeOption: unknown): maybeOption is Option<T>;
15
- static Some<T>(value: T): Option<T>;
16
- static None<T>(): Option<T>;
17
- [Symbol.toPrimitive](): string;
18
- isSome(): boolean;
19
- isNone(): boolean;
20
- equals(other: Option<T>): boolean;
21
- map<U>(f: (value: T) => U, { coalesce }?: {
22
- coalesce?: boolean | undefined;
23
- }): Option<U>;
24
- flatMap<U>(f: (value: T) => Option<U>): Option<U>;
25
- flatten(): T extends Option<infer U> ? Option<U> : Option<T>;
26
- orDefault(defaultValue: T): T;
27
- orNull(): T | null;
28
- orUndefined(): T | undefined;
29
- or<U>(other: Option<U>): Option<T> | Option<U>;
30
- unwrap(): T;
31
- filter<U extends T>(predicate: (value: T) => value is U): Option<U>;
32
- filter(predicate: (value: T) => boolean): Option<T>;
33
- toString(): string;
34
- }
35
- declare function arrayGet<T>(arr: T[], i: number): Option<T>;
36
- declare function arrayFind<T>(arr: T[], predicate: (item: T, i: number, arr: T[]) => boolean, thisArg?: any): Option<T>;
37
- declare function arrayFindLast<T>(arr: T[], predicate: (item: T, i: number, arr: T[]) => boolean, thisArg?: any): Option<T>;
38
- declare function arrayFindIndex<T>(arr: T[], predicate: (item: T, i: number, arr: T[]) => boolean, thisArg?: any): Option<number>;
39
- declare function arrayFindLastIndex<T>(arr: T[], predicate: (item: T, i: number, arr: T[]) => boolean, thisArg?: any): Option<number>;
40
- declare function arrayIndexOf<T>(arr: T[], item: T, fromIndex?: number): Option<number>;
41
- declare function arrayLastIndexOf<T>(arr: T[], item: T, fromIndex?: number): Option<number>;
42
- declare function arrPop<T>(arr: T[]): Option<T>;
43
- declare function arrShift<T>(arr: T[]): Option<T>;
44
-
45
- export { Option, arrPop, arrShift, arrayFind, arrayFindIndex, arrayFindLast, arrayFindLastIndex, arrayGet, arrayIndexOf, arrayLastIndexOf };
package/dist/option.js DELETED
@@ -1,163 +0,0 @@
1
- // src/option.ts
2
- var Option = class _Option {
3
- _kind;
4
- value;
5
- constructor(_kind, value = void 0) {
6
- this._kind = _kind;
7
- this.value = value;
8
- }
9
- *[Symbol.iterator]() {
10
- yield this;
11
- if (this.isNone())
12
- throw new Error("Tried to unwrap a None() via its iterator");
13
- else return this.value;
14
- }
15
- static do(f) {
16
- const gen = f();
17
- let iter = gen.next();
18
- while (!iter.done) {
19
- switch (iter.value._kind) {
20
- case "Some":
21
- iter = gen.next(iter.value.value);
22
- break;
23
- case "None":
24
- gen.return?.(void 0);
25
- return _Option.None();
26
- }
27
- }
28
- return _Option.Some(iter.value);
29
- }
30
- static from(maybeValue, { allowOptionLikePOJO = false } = {}) {
31
- if (maybeValue === void 0 || maybeValue === null)
32
- return _Option.None();
33
- else if (_Option.isOption(maybeValue)) return maybeValue;
34
- else if (allowOptionLikePOJO && maybeValue && typeof maybeValue == "object" && "_kind" in maybeValue && (maybeValue._kind == "Some" || maybeValue._kind == "None"))
35
- return new _Option(
36
- maybeValue._kind,
37
- maybeValue.value
38
- );
39
- else return _Option.Some(maybeValue);
40
- }
41
- static wrapFunction(f, { allowOptionLikePOJO = false } = {}) {
42
- return (...args) => _Option.from(f(...args), { allowOptionLikePOJO });
43
- }
44
- static isOption(maybeOption) {
45
- return maybeOption instanceof _Option;
46
- }
47
- static Some(value) {
48
- return new _Option("Some", value);
49
- }
50
- static #None = new _Option("None");
51
- static None() {
52
- return this.#None;
53
- }
54
- [Symbol.toPrimitive]() {
55
- return this.toString();
56
- }
57
- isSome() {
58
- return this._kind == "Some";
59
- }
60
- isNone() {
61
- return this._kind == "None";
62
- }
63
- equals(other) {
64
- if (this.isNone()) return other.isNone();
65
- else if (other.isNone()) return false;
66
- else return this.value == other.value;
67
- }
68
- map(f, { coalesce = false } = {}) {
69
- if (this.isNone()) return _Option.None();
70
- else if (coalesce) return _Option.from(f(this.value));
71
- else return _Option.Some(f(this.value));
72
- }
73
- flatMap(f) {
74
- if (this.isNone()) return _Option.None();
75
- else return f(this.value);
76
- }
77
- flatten() {
78
- if (this.isNone()) return _Option.None();
79
- else return _Option.isOption(this.value) ? this.value : this;
80
- }
81
- orDefault(defaultValue) {
82
- if (this.isNone()) return defaultValue;
83
- else return this.value;
84
- }
85
- orNull() {
86
- if (this.isNone()) return null;
87
- else return this.value;
88
- }
89
- orUndefined() {
90
- if (this.isNone()) return void 0;
91
- else return this.value;
92
- }
93
- or(other) {
94
- if (this.isNone()) return other;
95
- else return this;
96
- }
97
- unwrap() {
98
- if (this.isNone()) throw new Error("Tried to unwrap a None()");
99
- else return this.value;
100
- }
101
- filter(predicate) {
102
- if (this.isNone()) return this;
103
- else return predicate(this.value) ? this : _Option.None();
104
- }
105
- toString() {
106
- if (this.isNone()) return "None()";
107
- switch (typeof this.value) {
108
- case "string":
109
- return `Some("${this.value}")`;
110
- case "function":
111
- case "object":
112
- return `Some(${JSON.stringify(this.value)})`;
113
- default:
114
- return `Some(${this.value})`;
115
- }
116
- }
117
- };
118
- function arrayGet(arr, i) {
119
- if (i >= arr.length || i < 0) return Option.None();
120
- else return Option.Some(arr[i]);
121
- }
122
- function arrayFind(arr, predicate, thisArg) {
123
- return Option.from(arr.find(predicate, thisArg));
124
- }
125
- function arrayFindLast(arr, predicate, thisArg) {
126
- return Option.from(arr.findLast(predicate, thisArg));
127
- }
128
- function arrayFindIndex(arr, predicate, thisArg) {
129
- const idx = arr.findIndex(predicate, thisArg);
130
- return idx == -1 ? Option.None() : Option.Some(idx);
131
- }
132
- function arrayFindLastIndex(arr, predicate, thisArg) {
133
- const idx = arr.findLastIndex(predicate, thisArg);
134
- return idx == -1 ? Option.None() : Option.Some(idx);
135
- }
136
- function arrayIndexOf(arr, item, fromIndex) {
137
- const idx = arr.indexOf(item, fromIndex);
138
- return idx == -1 ? Option.None() : Option.Some(idx);
139
- }
140
- function arrayLastIndexOf(arr, item, fromIndex) {
141
- const idx = arr.lastIndexOf(item, fromIndex);
142
- return idx == -1 ? Option.None() : Option.Some(idx);
143
- }
144
- function arrPop(arr) {
145
- if (arr.length == 0) return Option.None();
146
- else return Option.Some(arr.pop());
147
- }
148
- function arrShift(arr) {
149
- if (arr.length == 0) return Option.None();
150
- else return Option.Some(arr.shift());
151
- }
152
- export {
153
- Option,
154
- arrPop,
155
- arrShift,
156
- arrayFind,
157
- arrayFindIndex,
158
- arrayFindLast,
159
- arrayFindLastIndex,
160
- arrayGet,
161
- arrayIndexOf,
162
- arrayLastIndexOf
163
- };
package/dist/random.js DELETED
@@ -1,86 +0,0 @@
1
- // src/random.ts
2
- var base_randi = make_randi(Math.random);
3
- function randi(minOrMax, max) {
4
- if (typeof max == "number") return base_randi(minOrMax, max);
5
- else return base_randi(minOrMax);
6
- }
7
- var base_randf = make_randf(Math.random);
8
- function randf(minOrMax, max) {
9
- if (typeof max == "number") return base_randf(minOrMax, max);
10
- else return base_randf(minOrMax);
11
- }
12
- var shuffle = make_shuffle(Math.random);
13
- function make_randi(prng) {
14
- return function randi2(minOrMax, max) {
15
- if (typeof max == "number") {
16
- const min = minOrMax;
17
- const delta = max - min;
18
- return min + Math.floor(prng() * delta);
19
- } else return Math.floor(prng() * minOrMax);
20
- };
21
- }
22
- function make_randf(prng) {
23
- return function randf2(minOrMax, max) {
24
- if (typeof max == "number") {
25
- const min = minOrMax;
26
- const delta = max - min;
27
- return min + prng() * delta;
28
- } else return prng() * minOrMax;
29
- };
30
- }
31
- function make_shuffle(prng) {
32
- const randi2 = make_randi(prng);
33
- return function shuffle2(arr) {
34
- const clone = Array.from(arr);
35
- for (let i = 0; i < clone.length - 2; i++) {
36
- const j = randi2(i, clone.length);
37
- const temp = clone[i];
38
- clone[i] = clone[j];
39
- clone[j] = temp;
40
- }
41
- return clone;
42
- };
43
- }
44
- function seeded(seed) {
45
- if (typeof seed == "string") seed = cyrb128(seed);
46
- else seed ^= 3735928559;
47
- const prng = splitmix32(seed);
48
- for (let i = 0; i < 15; i++) prng();
49
- return prng;
50
- }
51
- function cyrb128(str) {
52
- let h1 = 1779033703, h2 = 3144134277, h3 = 1013904242, h4 = 2773480762;
53
- for (let i = 0, k; i < str.length; i++) {
54
- k = str.charCodeAt(i);
55
- h1 = h2 ^ Math.imul(h1 ^ k, 597399067);
56
- h2 = h3 ^ Math.imul(h2 ^ k, 2869860233);
57
- h3 = h4 ^ Math.imul(h3 ^ k, 951274213);
58
- h4 = h1 ^ Math.imul(h4 ^ k, 2716044179);
59
- }
60
- h1 = Math.imul(h3 ^ h1 >>> 18, 597399067);
61
- h2 = Math.imul(h4 ^ h2 >>> 22, 2869860233);
62
- h3 = Math.imul(h1 ^ h3 >>> 17, 951274213);
63
- h4 = Math.imul(h2 ^ h4 >>> 19, 2716044179);
64
- h1 ^= h2 ^ h3 ^ h4;
65
- return h1 >>> 0;
66
- }
67
- function splitmix32(a) {
68
- return function() {
69
- a |= 0;
70
- a = a + 2654435769 | 0;
71
- let t = a ^ a >>> 16;
72
- t = Math.imul(t, 569420461);
73
- t = t ^ t >>> 15;
74
- t = Math.imul(t, 1935289751);
75
- return ((t = t ^ t >>> 15) >>> 0) / 4294967296;
76
- };
77
- }
78
- export {
79
- make_randf,
80
- make_randi,
81
- make_shuffle,
82
- randf,
83
- randi,
84
- seeded,
85
- shuffle
86
- };
package/dist/result.d.ts DELETED
@@ -1,56 +0,0 @@
1
- import { StandardSchemaV1 } from '@standard-schema/spec';
2
-
3
- declare class Result<Err extends Error, T> {
4
- value: T | null;
5
- error: Err | null;
6
- constructor(value: null, error: Err);
7
- constructor(value: T, error: null);
8
- asTuple(): [Err, null] | [null, T];
9
- asObject(): {
10
- value: null;
11
- error: Err;
12
- } | {
13
- value: T;
14
- error: null;
15
- };
16
- andThen<Err2 extends Error, F extends (value: T) => any>(f: F): ReturnType<F> extends Promise<infer U> ? AsyncResult<Err | Err2, U> : Result<Err | Err2, ReturnType<F>>;
17
- match(onValue: (value: T) => void): void;
18
- match<U>(onValue: (value: T) => U, onError: (error: Err) => U): U;
19
- recover<Err2 extends Error, F extends (error: Err) => T | Promise<T>>(f: F): ReturnType<F> extends Promise<T> ? AsyncResult<Err2, T> : Result<Err2, T>;
20
- unwrap(): T;
21
- unwrapErr(): Err;
22
- }
23
- declare class AsyncResult<Err extends Error, T> {
24
- promise: Promise<T>;
25
- constructor(promise: Promise<T>);
26
- asTuple(): Promise<[Err, null] | [null, T]>;
27
- asObject(): Promise<{
28
- value: null;
29
- error: Err;
30
- } | {
31
- value: T;
32
- error: null;
33
- }>;
34
- then<U>(cb: (value: Result<Err, T>) => U | Promise<U>): Promise<U>;
35
- andThen<Err2 extends Error, F extends (value: T) => any>(f: F): AsyncResult<Err | Err2, Awaited<ReturnType<F>>>;
36
- match(onValue: (value: T) => void): Promise<void>;
37
- match<U>(onValue: (value: T) => U, onError: (error: Err) => U): Promise<U>;
38
- recover<Err2 extends Error, F extends (error: Err) => T | Promise<T>>(f: F): AsyncResult<Err2, T>;
39
- unwrap(): Promise<T>;
40
- unwrapErr(): Promise<Err>;
41
- }
42
- declare function safe<Err extends Error, T>(promise: Promise<T>): AsyncResult<Error, T>;
43
- declare function safe<Err extends Error, F extends (...args: any) => Promise<any>>(f: F, ...args: Parameters<F>): AsyncResult<Err, Awaited<ReturnType<F>>>;
44
- declare function safe<Err extends Error, F extends (...args: any) => any>(f: F, ...args: Parameters<F>): Result<Err, ReturnType<F>>;
45
- declare class SafeFunctionValidationError extends Error {
46
- name: string;
47
- issues: StandardSchemaV1.FailureResult["issues"];
48
- constructor(message: string, issues: StandardSchemaV1.FailureResult["issues"], options?: ErrorOptions);
49
- }
50
- interface MakeSafeFnOptions<ParamsSchema extends StandardSchemaV1 | undefined, ReturnSchema extends StandardSchemaV1 | undefined> {
51
- paramsSchema?: ParamsSchema;
52
- returnSchema?: ReturnSchema;
53
- }
54
- declare function makeSafeFn<Err extends Error, ParamsSchema extends StandardSchemaV1 | undefined, ReturnSchema extends StandardSchemaV1 | undefined, F extends (...args: ParamsSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<ParamsSchema> : any) => ReturnSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<ReturnSchema> : any>(f: F, options?: MakeSafeFnOptions<ParamsSchema, ReturnSchema>): (...args: Parameters<F>) => Result<Err, ReturnType<F>>;
55
-
56
- export { AsyncResult, Result, SafeFunctionValidationError, makeSafeFn, safe };