Hyperlinkv0.8.0-beta.28

Hash

Hash.numberconsteffect/Hash.ts:336
(n: number): number

Computes a hash value for a number.

When to use

Use to hash a JavaScript number with Effect's numeric hash semantics.

Details

This function creates a hash value for numeric inputs, handling special cases like NaN, Infinity, and -Infinity with distinct hash values. It uses bitwise operations to ensure good distribution of hash values across different numeric inputs.

Example (Hashing numbers)

import { Hash } from "effect"

console.log(Hash.number(42)) // hash of 42
console.log(Hash.number(3.14)) // hash of 3.14
console.log(Hash.number(NaN)) // hash of "NaN"
console.log(Hash.number(Infinity)) // 0 (special case)

// Same numbers produce the same hash
console.log(Hash.number(100) === Hash.number(100)) // true
hashing
Source effect/Hash.ts:33619 lines
export const number = (n: number) => {
  if (n !== n) {
    return string("NaN")
  }
  if (n === Infinity) {
    return string("Infinity")
  }
  if (n === -Infinity) {
    return string("-Infinity")
  }
  let h = n | 0
  if (h !== n) {
    h ^= n * 0xffffffff
  }
  while (n > 0xffffffff) {
    h ^= n /= 0xffffffff
  }
  return optimize(h)
}
Referenced by 3 symbols