MCPcopy Create free account
hub / github.com/immutable-js/immutable-js / hash

Function hash

src/Hash.ts:5–48  ·  view source on GitHub ↗
(o: unknown)

Source from the content-addressed store, hash-verified

3const defaultValueOf = Object.prototype.valueOf;
4
5export function hash(o: unknown): number {
6 // eslint-disable-next-line eqeqeq
7 if (o == null) {
8 return hashNullish(o);
9 }
10
11 // @ts-expect-error don't care about object beeing typed as `{}` here
12 if (typeof o.hashCode === 'function') {
13 // Drop any high bits from accidentally long hash codes.
14 // @ts-expect-error don't care about object beeing typed as `{}` here
15 return smi(o.hashCode(o));
16 }
17
18 const v = valueOf(o);
19
20 // eslint-disable-next-line eqeqeq
21 if (v == null) {
22 return hashNullish(v);
23 }
24
25 switch (typeof v) {
26 case 'boolean':
27 // The hash values for built-in constants are a 1 value for each 5-byte
28 // shift region expect for the first, which encodes the value. This
29 // reduces the odds of a hash collision for these common values.
30 return v ? 0x42108421 : 0x42108420;
31 case 'number':
32 return hashNumber(v);
33 case 'string':
34 return v.length > STRING_HASH_CACHE_MIN_STRLEN
35 ? cachedHashString(v)
36 : hashString(v);
37 case 'object':
38 case 'function':
39 return hashJSObj(v);
40 case 'symbol':
41 return hashSymbol(v);
42 default:
43 if (typeof v.toString === 'function') {
44 return hashString(v.toString());
45 }
46 throw new Error('Value type ' + typeof v + ' cannot be hashed.');
47 }
48}
49
50function hashNullish(nullish: null | undefined): number {
51 return nullish === null ? 0x42108422 : /* undefined */ 0x42108423;

Callers 11

getMethod · 0.90
updateMethod · 0.90
getMethod · 0.90
updateMethod · 0.90
updateMethod · 0.90
updateMethod · 0.90
createNodesFunction · 0.90
hashCollectionFunction · 0.90
hashCollisionKeyFunction · 0.85
hash.tsFile · 0.85
Map.collision.tsFile · 0.85

Calls 10

smiFunction · 0.90
hashNullishFunction · 0.85
valueOfFunction · 0.85
hashNumberFunction · 0.85
cachedHashStringFunction · 0.85
hashStringFunction · 0.85
hashJSObjFunction · 0.85
hashSymbolFunction · 0.85
hashCodeMethod · 0.65
toStringMethod · 0.45

Tested by

no test coverage detected