GithubHelp home page GithubHelp logo

stable-hash's Introduction

stable-hash

A tiny and fast (481b unpkg) lib for "stably hashing" a JavaScript value. Originally created for SWR.

It's similar to JSON.stringify(value), but:

  1. Supports any JavaScript value (BigInt, NaN, Symbol, function, class, ...)
  2. Sorts object keys (stable)
  3. Supports circular objects

Use

yarn add stable-hash
import hash from 'stable-hash'

hash(anyJavaScriptValueHere) // returns a string

Examples

Primitive Value

hash(1)
hash('foo')
hash(true)
hash(undefined)
hash(null)
hash(NaN)

BigInt:

hash(1) === hash(1n)
hash(1) !== hash(2n)

Symbol:

hash(Symbol.for('foo')) === hash(Symbol.for('foo'))
hash(Symbol.for('foo')) === hash(Symbol('foo'))
hash(Symbol('foo')) === hash(Symbol('foo'))
hash(Symbol('foo')) !== hash(Symbol('bar'))

Since Symbols cannot be serialized, stable-hash simply uses its description as the hash.

Regex

hash(/foo/) === hash(/foo/)
hash(/foo/) !== hash(/bar/)

Date

hash(new Date(1)) === hash(new Date(1))

Array

hash([1, '2', [new Date(3)]]) === hash([1, '2', [new Date(3)]])
hash([1, 2]) !== hash([2, 1])

Circular:

const foo = []
foo.push(foo)
hash(foo) === hash(foo)

Object

hash({ foo: 'bar' }) === hash({ foo: 'bar' })
hash({ foo: { bar: 1 } }) === hash({ foo: { bar: 1 } })

Stable:

hash({ a: 1, b: 2, c: 3 }) === hash({ c: 3, b: 2, a: 1 })

Circular:

const foo = {}
foo.foo = foo
hash(foo) === hash(foo)

Function, Class, Set, Map, Buffer...

stable-hash guarantees reference consistency (===) for objects that the constructor isn't Object.

const foo = () => {}
hash(foo) === hash(foo)
hash(foo) !== hash(() => {})
class Foo {}
hash(Foo) === hash(Foo)
hash(Foo) !== hash(class {})
const foo = new Set([1])
hash(foo) === hash(foo)
hash(foo) !== hash(new Set([1]))

Notes

This function does something similar to JSON.stringify, but more than it. It doesn't generate a secure checksum, which usually has a fixed length and is hard to be reversed. With stable-hash it's still possible to get the original data. Also, the output might include any charaters, not just alphabets and numbers like other hash algorithms. So:

  • Use another encoding layer on top of it if you want to display the output.
  • Use another crypto layer on top of it if you want to have a secure and fixed length hash.
import crypto from 'crypto'
import hash from 'stable-hash'

const weakHash = hash(anyJavaScriptValueHere)
const encodedHash = Buffer.from(weakHash).toString('base64')
const safeHash = crypto.createHash('MD5').update(weakHash).digest('hex')

Also, the consistency of this lib is sometimes guaranteed by the singularity of the WeakMap instance. So it might not generate the consistent results when running in different runtimes, e.g. server/client or parent/worker scenarios.

License

Created by Shu Ding. Released under the MIT License.

stable-hash's People

Contributors

dimamachina avatar intrnl avatar kenakafrosty avatar kikobeats avatar monstrag avatar paul-sachs avatar remidewitte avatar shuding avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

stable-hash's Issues

Isomorphic objects with circular references

const o1 = {}; o1.o = o1
const o2 = {}; o2.o = o2

hash(o1) !== hash(o2) // bug!

To fix this problem, we need an extra WeakMap and a reference counter only for recursive hash executions.

TypeError: default is not a function

I created index.d.ts file with following code:

declare module "stable-hash" {
  export default function stablehash(key: unknown): string;
}

Also tried this:

declare module "stable-hash" {
  function stablehash(key: unknown): string;
  export = stablehash;
}

In both cases got error TypeError: default is not a function when run unit tests using vitest. How to fix this error?

Missing types

It would by nice if there were TS intellisense. Since the lib is so simple, we could use a basic index.d.ts file.

Unit tests

It would be great to have some unit tests, just one simple script file is enough.

Add note about consistency

The consistency of this lib is sometimes guaranteed by the singularity of the WeakMap instance. So we should add some notes that it might have issue of consistency with multiple instances, e.g. server/client or parent/worker.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.