hash.ts


Overview

The hash.ts file implements a stable hashing utility designed to generate consistent, unique string representations (hashes) for arbitrary JavaScript values, including complex objects, arrays, and special types like Dates and RegExps. Unlike typical serialization (e.g., JSON.stringify), this hash function:

This utility is especially suitable when you need to quickly generate unique keys for complex, nested data structures in memory while avoiding performance bottlenecks and memory leaks.


Detailed Explanations

Imported utilities


Constants and Variables


Helper Functions

getTypeName(value: any): string

Usage example:

getTypeName(new Date()); // '[object Date]'
getTypeName({});         // '[object Object]'

isObjectTypeName(typeName: string, type: string): boolean

Usage example:

isObjectTypeName('[object Date]', 'Date'); // true
isObjectTypeName('[object Array]', 'Object'); // false

Main Exported Function

stableHash(arg: any): string

Generates a stable, unique hash string for the input value arg.

Parameters
Returns
Description and Algorithm
  1. Type detection:
    Determines the type of arg using typeof and internal toString checks.

  2. Special handling for objects:

    • If arg is a non-null object/function (excluding Date and RegExp), the function:

      • Checks if arg has already been hashed by looking it up in table.

      • If found, returns the cached hash string immediately (fast O(1) lookup).

      • Otherwise, assigns a temporary ID (counter incremented plus '~') and stores it in table to detect circular references during recursion.

      • If arg is an array, recursively hashes each element and concatenates results prefixed with '@'.

      • If arg is a plain object, sorts its keys alphabetically, recursively hashes each key-value pair, and concatenates results prefixed with '#'.

  3. Primitive and special types:

    • For Dates, uses toJSON() to get a standardized string.

    • For Symbols, uses toString().

    • For strings, JSON stringifies them.

    • For other primitives, converts to string.

  4. Returns the resulting hash string.

Usage Examples
import { stableHash } from './hash'

const obj = { b: 2, a: 1 }
console.log(stableHash(obj)) // Output: '#a:1,b:2,' (keys sorted)

const arr = [1, 2, { x: 10 }]
console.log(stableHash(arr)) // Output: '@1,2,#x:10,'

const circular: any = {}
circular.self = circular
console.log(stableHash(circular)) // Handles circular reference gracefully

Important Implementation Details


Interaction with Other Parts of the System


Mermaid Diagram: Class and Function Structure

flowchart TD
    A[stableHash(arg: any): string]
    A --> B[getTypeName(value: any): string]
    A --> C[isObjectTypeName(typeName: string, type: string): boolean]
    A --> D[table: WeakMap<object, string|number>]
    A --> E[counter: number]
    B --> F[OBJECT.prototype.toString.call(value)]
    C --> G[Compare typeName to expected '[object Type]']

Summary

The hash.ts file provides a robust, efficient, and stable hashing mechanism for arbitrary JavaScript values. It is optimized for performance with object caching, handles complex and circular structures, and produces consistent outputs by sorting keys. This utility is essential for scenarios requiring reliable, quick identification of data values without relying on full serialization or risking memory leaks.