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
|
// format as hex number
export const hex = (n) => '0x' + n.toString(16);
// concatenate Uint8Array
export const concat = (a, b) => {
const arr = new Uint8Array(a.length + b.length);
arr.set(a);
arr.set(b, a.length);
return arr;
};
// like Array.reduce() but await each iteration
export const areduce = async (array, fn, state=null) => {
for (const val of array) {
state = await fn(val, state);
}
return state;
};
// generate array with range [a, b[ or [0, a[
export const range = (a, b=null) => {
if (b === null) {
b = a;
a = 0;
}
const res = [];
for (let i = a; i < b; i++)
res.push(i);
return res;
};
// return a Promise that resolves in n seconds
export const sleep = (n) => new Promise(res => setTimeout(res, n*1000));
// hash an ArrayBuffer
export const hash = (data, seed = 0) => {
let h1 = 0xdeadbeef ^ seed;
let h2 = 0x41c6ce57 ^ seed;
data = new Uint8Array(data);
for (const byte of data) {
h1 = Math.imul(h1 ^ byte, 2654435761);
h2 = Math.imul(h2 ^ byte, 1597334677);
}
h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507);
h1 ^= Math.imul(h2 ^ (h2 >>> 13), 3266489909);
h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507);
h2 ^= Math.imul(h1 ^ (h1 >>> 13), 3266489909);
return 4294967296 * (2097151 & h2) + (h1 >>> 0);
};
|