Back

hashCode - typescript snippet

2021-01-01

Source Code

1/* eslint-disable no-bitwise */
2export const hashCode = (str: string, seed = 0) => {
3 if (!str) {
4 return '';
5 }
6
7 let h1 = 0xdeadbeef ^ seed;
8 let h2 = 0x41c6ce57 ^ seed;
9
10 for (let i = 0, ch; i < str.length; i += 1) {
11 ch = str.charCodeAt(i);
12 h1 = Math.imul(h1 ^ ch, 2654435761);
13 h2 = Math.imul(h2 ^ ch, 1597334677);
14 }
15 h1 =
16 Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^
17 Math.imul(h2 ^ (h2 >>> 13), 3266489909);
18
19 h2 =
20 Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^
21 Math.imul(h1 ^ (h1 >>> 13), 3266489909);
22 const ret = 4294967296 * (2097151 & h2) + (h1 >>> 0);
23
24 return ret.toString();
25};
26export const generateNewPK = () => hashCode(new Date().getTime().toString());
27

Execution Results

1hashCode("1a2bc3") === "4710200255027214"
2hashCode("hello") === "4625896200565286"
3hashCode("123") === "2502665170145887"