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