ohash

repository·main·Indexed 20 days ago

https://github.com/unjs/ohash

A JavaScript utility library for simple object hashing, serialization, and deep comparison. It provides functions to convert JS values into string hashes via `hash()`, generate stable string representations with `serialize()`, create SHA-256 digests using `digest()`, and perform deep equality checks with `isEqual()`. Additionally, it includes a `diff()` utility to identify added, removed, or changed properties between two objects.

Tokens
2.3K
Snippets
15
Records
17
Agent score
71%

What's inside ohash

  1. Import ohash

    main

    You can import the core functions or the utility functions using ESM or dynamic imports. The core functions are available from ohash, while diff is available from ohash/utils.

    // ESM import
    import { hash, serialize, digest, isEqual } from "ohash";
    import { diff } from "ohash/utils";
    
    // Dynamic import
    const { hash, serialize, digest, isEqual } = await import("ohash");
    const { diff } = await import("ohash/utils");
  2. Serialize a value with serialize(input)

    main

    The serialize(input) function converts an input value into a string representation used for hashing.

    IMPORTANT

    serialize uses best efforts to generate stable values, but it is not designed for security purposes. It may be susceptible to intentional collisions via user input.

    import { serialize } from "ohash";
    
    // "{foo:'bar'}"
    console.log(serialize({ foo: "bar" }));
  3. Find differences between objects with diff(obj1, obj2)

    main

    The diff(obj1, obj2) utility function compares two objects using nested serialization and returns an array of changes. Each entry in the returned array contains $key, $hash, $value, and $props. When logged, it displays a human-readable changelog string.

    import { diff } from "ohash/utils";
    
    const createObject = () => ({
      foo: "bar",
      nested: {
        y: 123,
        bar: {
          baz: "123",
        },
      },
    });
    
    const obj1 = createObject();
    const obj2 = createObject();
    
    obj2.nested.x = 123;
    delete obj2.nested.y;
    obj2.nested.bar.baz = 123;
    
    const diff = diff(obj1, obj2);
    
    // [-] Removed nested.y
    // [~] Changed nested.bar.baz from "123" to 123
    // [+] Added   nested.x
    console.log(diff(obj1, obj2));
  4. Hash a string with digest(str)

    main

    The digest(str) function hashes a string using the SHA-256 algorithm and encodes the output in Base64URL format.

    import { digest } from "ohash";
    
    // "f4OxZX_x_FO5LcGBSKHWXfwtSx-j1ncoSt3SABJtkGk"
    console.log(digest("Hello World!"));
  5. Compare objects with isEqual(obj1, obj2)

    main

    The isEqual(obj1, obj2) function compares two objects. It first attempts a strict equality check (===) and falls back to comparing their serialized values if the strict check fails.

    import { isEqual } from "ohash";
    
    // true
    console.log(isEqual({ a: 1, b: 2 }, { b: 2, a: 1 }));
  6. Serialize values into a stable string with serialize()

    main

    The serialize(input) function converts any JavaScript value into a stable string representation suitable for hashing. This is useful when you need a consistent string identifier for complex objects, arrays, or primitives.

    Important Security Note: This method is designed for stability, not security. It is not intended for cryptographic purposes and is susceptible to intentional collisions via user input.

    Supported types and their serialization styles include:

    • Strings: Wrapped in single quotes (e.g., 'hello').
    • BigInt: Appended with n (e.g., 10n).
    • Null: Returns `
  7. Calculate differences between two objects with diff()

    main

    The diff(obj1, obj2) function compares two objects and returns an array of DiffEntry objects representing the changes. It identifies whether properties were added, removed, or changed by traversing the object structure and comparing their hashed representations.

    import { diff } from "ohash";
    
    const obj1 = { a: 1, b: { c: 2 } };
    const obj2 = { a: 1, b: { c: 3 }, d: 4 };
    
    const differences = diff(obj1, obj2);
    // Returns an array of DiffEntry objects describing the changes to 'b.c' and 'd'
  8. Compare objects with isEqual()

    main

    The isEqual function performs a comparison between two values using a two-step process: first, it checks for strict reference equality (===), and if that fails, it checks for equality using stable deep hashing via serialize(). This ensures that two different object instances with the same structure and values are considered equal.

    import { isEqual } from 'ohash';
    
    const obj1 = { a: 1, b: { c: 2 } };
    const obj2 = { a: 1, b: { c: 2 } };
    
    // Returns true because they are structurally identical
    isEqual(obj1, obj2); 
  9. Hash any JS value with hash()

    main

    The hash function converts any JavaScript value into a unique string hash. It works by first serializing the input value and then applying a cryptographic digest to the resulting string. This is useful for creating stable identifiers for complex objects, arrays, or primitives.

    import { hash } from 'ohash'
    
    const myHash = hash({ a: 1, b: [1, 2, 3] })
    // returns a string hash
  10. Hash an input with hash()

    main

    Use the hash function to generate a hash of a given input. This is typically used for creating unique identifiers for data structures.

    import { hash } from 'ohash';
    
    const h = hash({ a: 1, b: 2 });