UNPKG

1.81 kBJavaScriptView Raw
1/**
2 * Copyright (c) Facebook, Inc. and its affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 *
7 * Based on implementations by Gary Court and Austin Appleby, 2011, MIT.
8 *
9 * strict
10 * @format
11 */
12'use strict';
13
14var BASE62 = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
15/**
16 * @param {string} key A UTF-16 or ASCII string
17 * @return {string} a base62 murmur hash
18 */
19
20function murmurHash(str) {
21 /* eslint-disable no-bitwise */
22 var length = str.length;
23 var rem = length & 3;
24 var len = length ^ rem;
25 var h = 0;
26 var i = 0;
27 var k;
28
29 while (i !== len) {
30 var ch4 = str.charCodeAt(i + 3);
31 k = str.charCodeAt(i) ^ str.charCodeAt(i + 1) << 8 ^ str.charCodeAt(i + 2) << 16 ^ (ch4 & 0xff) << 24 ^ (ch4 & 0xff00) >> 8;
32 i += 4;
33 k = k * 0x2d51 + (k & 0xffff) * 0xcc9e0000 >>> 0;
34 k = k << 15 | k >>> 17;
35 k = k * 0x3593 + (k & 0xffff) * 0x1b870000 >>> 0;
36 h ^= k;
37 h = h << 13 | h >>> 19;
38 h = h * 5 + 0xe6546b64 >>> 0;
39 }
40
41 k = 0;
42
43 switch (rem) {
44 /* eslint-disable no-fallthrough */
45 case 3:
46 k ^= str.charCodeAt(len + 2) << 16;
47
48 case 2:
49 k ^= str.charCodeAt(len + 1) << 8;
50
51 case 1:
52 k ^= str.charCodeAt(len);
53 k = k * 0x2d51 + (k & 0xffff) * 0xcc9e0000 >>> 0;
54 k = k << 15 | k >>> 17;
55 k = k * 0x3593 + (k & 0xffff) * 0x1b870000 >>> 0;
56 h ^= k;
57 }
58
59 h ^= length;
60 h ^= h >>> 16;
61 h = h * 0xca6b + (h & 0xffff) * 0x85eb0000 >>> 0;
62 h ^= h >>> 13;
63 h = h * 0xae35 + (h & 0xffff) * 0xc2b20000 >>> 0;
64 h ^= h >>> 16;
65 h >>>= 0;
66
67 if (!h) {
68 return '0';
69 }
70
71 var s = '';
72
73 while (h) {
74 var d = h % 62;
75 s = BASE62[d] + s;
76 h = (h - d) / 62;
77 }
78
79 return s;
80}
81
82module.exports = murmurHash;
\No newline at end of file