Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/extensions/json-language-features/client/src/utils/hash.ts
3322 views
1
/*---------------------------------------------------------------------------------------------
2
* Copyright (c) Microsoft Corporation. All rights reserved.
3
* Licensed under the MIT License. See License.txt in the project root for license information.
4
*--------------------------------------------------------------------------------------------*/
5
6
/**
7
* Return a hash value for an object.
8
*/
9
export function hash(obj: any, hashVal = 0): number {
10
switch (typeof obj) {
11
case 'object':
12
if (obj === null) {
13
return numberHash(349, hashVal);
14
} else if (Array.isArray(obj)) {
15
return arrayHash(obj, hashVal);
16
}
17
return objectHash(obj, hashVal);
18
case 'string':
19
return stringHash(obj, hashVal);
20
case 'boolean':
21
return booleanHash(obj, hashVal);
22
case 'number':
23
return numberHash(obj, hashVal);
24
case 'undefined':
25
return 937 * 31;
26
default:
27
return numberHash(obj, 617);
28
}
29
}
30
31
function numberHash(val: number, initialHashVal: number): number {
32
return (((initialHashVal << 5) - initialHashVal) + val) | 0; // hashVal * 31 + ch, keep as int32
33
}
34
35
function booleanHash(b: boolean, initialHashVal: number): number {
36
return numberHash(b ? 433 : 863, initialHashVal);
37
}
38
39
function stringHash(s: string, hashVal: number) {
40
hashVal = numberHash(149417, hashVal);
41
for (let i = 0, length = s.length; i < length; i++) {
42
hashVal = numberHash(s.charCodeAt(i), hashVal);
43
}
44
return hashVal;
45
}
46
47
function arrayHash(arr: any[], initialHashVal: number): number {
48
initialHashVal = numberHash(104579, initialHashVal);
49
return arr.reduce((hashVal, item) => hash(item, hashVal), initialHashVal);
50
}
51
52
function objectHash(obj: any, initialHashVal: number): number {
53
initialHashVal = numberHash(181387, initialHashVal);
54
return Object.keys(obj).sort().reduce((hashVal, key) => {
55
hashVal = stringHash(key, hashVal);
56
return hash(obj[key], hashVal);
57
}, initialHashVal);
58
}
59
60