Hyperlinkv0.8.0-beta.28

Hash

Hash.hashconsteffect/Hash.ts:110
<A>(self: A): number

Computes a hash value for any given value.

When to use

Use to compute an Effect hash for primitives, collections, and hashable objects.

Details

This function can hash primitives (numbers, strings, booleans, etc.) as well as objects, arrays, and other complex data structures. It automatically handles different types and provides a consistent hash value for equivalent inputs.

Gotchas

Objects being hashed must be treated as immutable after their first hash computation. Hash results are cached, so mutating an object after hashing will lead to stale cached values and broken hash-based operations. For mutable objects, implement a custom Hash interface that hashes the object reference rather than its content.

Example (Hashing different values)

import { Hash } from "effect"

// Hash primitive values
console.log(Hash.hash(42)) // numeric hash
console.log(Hash.hash("hello")) // string hash
console.log(Hash.hash(true)) // boolean hash

// Hash objects and arrays
console.log(Hash.hash({ name: "John", age: 30 }))
console.log(Hash.hash([1, 2, 3]))
console.log(Hash.hash({ id: "user-1", roles: ["admin", "editor"] }))
hashing
Source effect/Hash.ts:11053 lines
export const hash: <A>(self: A) => number = <A>(self: A) => {
  switch (typeof self) {
    case "number":
      return number(self)
    case "bigint":
      return string(self.toString(10))
    case "boolean":
      return string(String(self))
    case "symbol":
      return string(String(self))
    case "string":
      return string(self)
    case "undefined":
      return string("undefined")
    case "function":
    case "object": {
      if (self === null) {
        return string("null")
      } else if (self instanceof Date) {
        return string(self.toISOString())
      } else if (self instanceof RegExp) {
        return string(self.toString())
      } else {
        if (byReferenceInstances.has(self)) {
          return random(self)
        }
        if (hashCache.has(self)) {
          return hashCache.get(self)!
        }
        const h = withVisitedTracking(self, () => {
          if (isHash(self)) {
            return self[symbol]()
          } else if (typeof self === "function") {
            return random(self)
          } else if (Array.isArray(self) || ArrayBuffer.isView(self)) {
            return array(self as any)
          } else if (self instanceof Map) {
            return hashMap(self)
          } else if (self instanceof Set) {
            return hashSet(self)
          }
          return structure(self)
        })
        hashCache.set(self, h)
        return h
      }
    }
    default:
      throw new Error(
        `BUG: unhandled typeof ${typeof self} - please report an issue at https://github.com/Effect-TS/effect/issues`
      )
  }
}
Referenced by 6 symbols