-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.ts
180 lines (167 loc) · 5.09 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
/**
* @file utils.ts
* @author Brandon Kalinowski
* @description A collection of useful small functions in one location.
* @copyright 2020-2024 Brandon Kalinowski
* @license MIT
*/
/**
* Does what it says on the tin.
* Used by printYaml for more compact YAML text.
*/
export function stripUndefined<T extends Record<string, any>>(obj: T): T {
if (typeof obj === "undefined") return obj;
Object.keys(obj).forEach((key) => {
if (obj[key] && typeof obj[key] === "object") stripUndefined(obj[key]);
else if (obj[key] === undefined) delete obj[key];
});
return obj;
}
/**
* Returns true if x is an object, false otherwise.
*/
export function isObject(o: unknown): o is Record<string | symbol, any> {
return typeof o === "object" && !Array.isArray(o) && !!o;
}
/**
* An primitive item that can be encoded as JSON or undefined (not object)
*/
export type jsonItem = string | number | null | undefined | boolean;
/**
* Visitor is a function that performs a modification on a visited object value.
*/
export type Visitor = (item: jsonItem) => jsonItem;
/**
* visitAll recursively visits all values of an object and
* applies a visitor function to each primitive value it encounters.
* @param item An item to modify
* @param visitor A function that updates primitives
*/
export function visitAll(item: unknown, visitor: Visitor): unknown {
if (item === null || item === undefined) {
return visitor(item);
} else if (Array.isArray(item)) {
return item.map((v) => {
return visitAll(v, visitor);
});
} else if (isObject(item)) {
Object.entries(item).forEach(([key, value]) => {
item[key] = visitAll(value, visitor);
});
} else {
return visitor(item as string);
}
return item;
}
/**
* dotPath returns the value for a given object path.
* @param object An object to search
* @param path is a dot seperated string or an array of nested keys
* @param defaultValue An optional value to return if value not found
*/
export function dotProp(
object: any,
path: string | string[],
defaultValue?: any,
) {
if (!isObject(object)) {
throw new TypeError(`Expected object but got ${object}`);
}
const pathArray = typeof path === "string" ? path.split(".") : path;
if (pathArray.length === 0) {
return;
}
for (let i = 0; i < pathArray.length; i++) {
if (!Object.prototype.propertyIsEnumerable.call(object, pathArray[i])) {
return defaultValue;
}
object = object[pathArray[i]];
if (object === undefined || object === null) {
// `object` is either `undefined` or `null` so we want to stop the loop, and
// if this is not the last bit of the path, and
// if it did't return `undefined`
// it would return `null` if `object` is `null`
// but we want `get({foo: null}, 'foo.bar')` to equal `undefined`, or the supplied value, not `null`
if (i !== pathArray.length - 1) {
return defaultValue;
}
break;
}
}
return object;
}
/**
* notImplemented returns a function that throws if called.
*/
export function notImplemented(name: string) {
return (..._: any[]) => {
throw new Error(`${name} is not implemented.`);
};
}
/**
* wait builds a promise that resolves after a certain time and a function to cancel the timer.
* @param time the number of milliseconds to wait
* @param msg An object to return when the timer completes
* @param id An optional id to assign the setTimout to.
*/
export function wait<T>(
time: number,
msg?: T,
reject = false,
id?: any,
): [Promise<T>, () => void] {
function makeResolver(action: (arg: any) => void) {
//prettier-ignore
id = setTimeout(() => action(msg), time);
}
return [
new Promise((resolver, rejecter) =>
makeResolver(reject ? rejecter : resolver)
),
() => clearTimeout(id),
];
}
/**
* withTimeout returns a new promise that resolves when the promise resolves or the timeout occurs.
*
* NOTE: Deno has issues with inferring generics see https://github.com/denoland/deno/issues/3997.
* For now, just pass explicit generic parameters
* @param ms specify timeout in milliseconds
* @param promise a function that returns a promise. Be sure to call bind if it is a method.
* @param timoutMsg Specify an object to return if the timeout occurs
*/
export async function withTimeout<V, TO>(
ms: number,
promise: () => Promise<V>,
timoutMsg?: TO,
rejectOnTimeout = false,
): Promise<V | TO> {
const [waiting, cancel] = wait(ms, timoutMsg, rejectOnTimeout);
const result = await Promise.race([promise(), waiting]);
cancel();
return result as V | TO;
}
/**
* A tagged template function that behaves like an untagged template literal.
* This is useful for syntax highlighting tagged templates. i.e. import as yaml.
*/
export function vanillaTag(literals: TemplateStringsArray, ...expr: unknown[]) {
return String.raw({ raw: literals } as any, ...expr);
}
/**
* Locate the user's home directory.
* Requires `--allow-env`
*/
export function homedir() {
return (
Deno.env.get("HOME") ||
Deno.env.get("HOMEPATH") ||
Deno.env.get("USERPROFILE")
);
}
/** stringify item to string */
export function asString(data: any) {
let errStr = String(data);
if (errStr === "[object Object]") errStr = JSON.stringify(data);
return errStr;
}