-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.ts
75 lines (59 loc) · 1.96 KB
/
utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import assert = require("assert");
export type AbsPath = `/${string}`;
export type HttpUrl = `http://${string}`;
// Like `optionals` from Nixpkgs, returns [] if the condition is false.
export function optionals<T>(cond: any, ...args: T[]): T[] {
return cond ? args : [];
}
export function mapObject(
obj: { [key: string]: any },
fn: (value: any, key: string, obj: any) => any
): { [key: string]: any } {
return Object.fromEntries(
Object.entries(obj).map(([key, value]) => [key, fn(value, key, obj)])
);
}
export function deleteUndefined<T extends {}>(obj: T): T {
mapObject(obj, (v, k, o) => {
if (v === undefined) {
delete o[k];
} else if (typeof v === "object") {
deleteUndefined(v);
}
});
return obj;
}
assert.deepStrictEqual(deleteUndefined({ a: 1, b: undefined }), { a: 1 });
export function sortObject(obj: any): any {
return typeof obj === "object" && !Array.isArray(obj) && obj !== null
? Object.keys(obj)
.sort()
.reduce((p: any, k: string) => ((p[k] = obj[k]), p), {})
: obj;
}
assert.deepStrictEqual(sortObject({ b: 2, a: 1 }), { a: 1, b: 2 });
export function stableStringify(obj: any): string {
return JSON.stringify(obj, (_, v) => sortObject(v));
}
assert.strictEqual(stableStringify({ b: 2, a: 1 }), '{"a":1,"b":2}');
export function isEqual(a: any, b: any): boolean {
return stableStringify(a) === stableStringify(b);
}
assert(isEqual({ b: 2, a: 1 }, { a: 1, b: 2, c: undefined }));
export function isValidUint(x: number): boolean {
return x >= 0 && Number.isSafeInteger(x); // returns false for NaN
}
assert(isValidUint(0));
assert(isValidUint(1));
assert(!isValidUint(-1));
assert(!isValidUint(1.1));
assert(!isValidUint(NaN));
export function trueOr1(val?: string): boolean {
return ["true", "1"].includes(val!); // handles undefined just fine
}
assert(trueOr1("true"));
assert(trueOr1("1"));
assert(!trueOr1("false"));
assert(!trueOr1("0"));
assert(!trueOr1(undefined));
assert(!trueOr1("blah"));