Skip to content

Function: objectHash() ​

objectHash(value, options?): string

Hash any value by its content: two values which are deeply equal get the same hash, whatever their identity or the order of their keys (a cache key, a change detection, a deduplication). The value is serialized with its types (1 and '1' differ, and so do two classes with the same properties), then hashed.

Supported: the primitives, plain objects and class instances (their own enumerable string keys; the symbol keys are ignored), arrays, Date (an invalid date too), RegExp, Error (its toString()), Map and Set, URL, the typed arrays, ArrayBuffer, Buffer and functions (their source code). A circular reference is hashed as a reference, not followed.

Parameters ​

value ​

any

The value to hash; it must not be undefined.

options? ​

ObjectHashOptions

The algorithm and the encoding of the digest, and what counts in the hash.

Returns ​

string

The digest, in hexadecimal by default (a SHA-1: 40 characters); the serialization with the 'passthrough' algorithm.

Throws ​

When value is undefined, when the algorithm or the encoding is not supported, or when the value contains an unsupported type (a Promise, a WeakMap, a Blob…) without ignoreUnknown.

Example ​

typescript
import {objectHash} from 'lakutata/utils'

console.log(objectHash({a: 1, b: [1, 2]}) === objectHash({b: [1, 2], a: 1}))
//true
console.log(objectHash([1, 2]) === objectHash([2, 1]))
//false
console.log(objectHash([1, 2], {unorderedArrays: true}) === objectHash([2, 1], {unorderedArrays: true}))
//true
//A cache key ignoring the timestamps
const key: string = objectHash({query: 'books', at: Date.now()}, {
    algorithm: 'sha256',
    excludeKeys: (name: string): boolean => name === 'at'
})
console.log(key.length)
//64

Released under the MIT License.