-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.mjs
77 lines (67 loc) · 2.3 KB
/
util.mjs
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
// not thrilled this uses idx, would rather do destructuring and not rely on idx/length
// would also like to see this done with a generator
export function combinations(obj) {
const keys = Object.keys(obj);
const values = Object.values(obj);
function gen(values, idx) {
if (idx === values.length) {
return [{}]; // Base case: return an array with an empty object
}
const current = values[idx];
const remaining = gen(values, idx + 1); // recurse
const combos = [];
for (const item of current) {
for (const combination of remaining) {
combos.push({ ...combination, [keys[idx]]: item }); // Combine the current item with each of the combinations from the rest
}
}
return combos;
}
return gen(values, 0);
}
export const range = (min, max /* [min, max] */) =>
[...Array(max - min + 1).keys()].map((i) => i + min);
export function fail(msg) {
// eslint-disable-next-line no-alert
alert(msg);
}
export function datatypeToTypedArray(datatype) {
switch (datatype) {
case "f32":
return Float32Array;
case "i32":
return Int32Array;
case "u32":
return Uint32Array;
}
return undefined;
}
export function datatypeToBytes(datatype) {
switch (datatype) {
case "f32":
return Float32Array.BYTES_PER_ELEMENT;
case "i32":
return Int32Array.BYTES_PER_ELEMENT;
case "u32":
return Uint32Array.BYTES_PER_ELEMENT;
}
return undefined;
}
// https://stackoverflow.com/questions/8896327/jquery-wait-delay-1-second-without-executing-code
export const delay = (millis) =>
new Promise((resolve, reject) => {
setTimeout((_) => resolve(), millis);
});
// https://stackoverflow.com/questions/3665115/how-to-create-a-file-in-memory-for-user-to-download-but-not-through-server
export function download(content, mimeType, filename) {
const a = document.createElement("a"); // Create "a" element
if (mimeType == "application/json") {
content = JSON.stringify(content);
}
const blob = new Blob([content], { type: mimeType }); // Create a blob (file-like object)
const url = URL.createObjectURL(blob); // Create an object URL from blob
a.setAttribute("href", url); // Set "a" element link
a.setAttribute("download", filename); // Set download filename
a.click(); // Start downloading
URL.revokeObjectURL(url);
}