-
Notifications
You must be signed in to change notification settings - Fork 5
/
hash.ts
31 lines (31 loc) · 842 Bytes
/
hash.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
function normalizeAsArray(obj: object): any {
if (obj === null) {
return null;
}
if (Array.isArray(obj)) {
return obj.map((v) => normalizeAsArray(v));
} else if (typeof obj === 'object') {
const arr = [];
const keys = Object.keys(obj).sort();
for (const key of keys) {
const value = (obj as any)[key];
if (value) {
arr.push([key, normalizeAsArray(value)]);
}
}
return arr;
} else {
return obj;
}
}
export function simple_hash(obj: any): string {
const str = typeof obj === 'string' ? obj : JSON.stringify(normalizeAsArray(obj as object)).replace(/\s+/g, '');
let hash = 0;
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i);
hash = (hash << 5) - hash + char;
hash &= hash; // Convert to 32bit integer
}
const result = new Uint32Array([hash])[0].toString(36);
return result;
}