• Stars
    star
    255
  • Rank 159,729 (Top 4 %)
  • Language
    TypeScript
  • Created about 3 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Stable JS value hash

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.

More Repositories

1

nextra

Simple, powerful and flexible site generation framework with everything you love from Next.js.
TypeScript
11,739
star
2

react-wrap-balancer

Simple React Component That Makes Titles More Readable
HTML
3,994
star
3

cobe

5kB WebGL globe lib.
MDX
3,227
star
4

tilg

A magical React Hook that helps you debug components.
TypeScript
2,133
star
5

next-view-transitions

Use CSS View Transitions API in Next.js App Router.
TypeScript
1,781
star
6

nextra-docs-template

Nextra docs template
MDX
1,023
star
7

y86

A Y86 pipeline CPU simulator in JavaScript.
JavaScript
525
star
8

apple-pencil-safari-api-test

Canvas based sketch board, with force touch and real-time Bezier curves.
JavaScript
454
star
9

yoga-wasm-web

WASM build of Yoga, targeting the web worker runtime.
TypeScript
186
star
10

cssosx

A CSS & JS made macOS UI.
CSS
135
star
11

next-cms

JavaScript
99
star
12

satori-syntax-highlighter

JavaScript
78
star
13

berlin-apartments

Information of apartments in Berlin for digital nomads.
73
star
14

cc

Shu's Creative Coding template.
JavaScript
71
star
15

site

JavaScript
67
star
16

swr-rsc-example

Example of useSWR + SSR/RSC
TypeScript
57
star
17

charch

中文网页排版工具
JavaScript
53
star
18

photos

JavaScript
47
star
19

100-days-ui

Turn @npaulflavius's 100 Days UI design into React components!
JavaScript
38
star
20

ding

(deprecated) A douban FM client in OS X (web application).
JavaScript
35
star
21

css-computer

Computational Style Sheets
HTML
34
star
22

blog-template

JavaScript
29
star
23

flappybird

Flappy Bird in JS.
JavaScript
29
star
24

vrs

WebGL + React + VR experiment. Demo:
JavaScript
29
star
25

coverflow

Apple’s Coverflow UI effect.
HTML
26
star
26

nextra-theme-docs

A documentation site theme for Nextra.
JavaScript
21
star
27

satori

Highly experimental, do not use in prod.
JavaScript
20
star
28

random-branch

A Raycast plugin to generate random git branch names.
TypeScript
17
star
29

request-cancellation-test

Test the browser request cancellation behavior.
JavaScript
16
star
30

coursejs

Create online simple & nice courses, just in 3 minutes.
JavaScript
15
star
31

scheme

A TOY Scheme interpreter implemented with JavaScript.
JavaScript
14
star
32

labs

labs
JavaScript
13
star
33

nextra-theme-blog

A blog site theme for Nextra.
JavaScript
13
star
34

animator

Canvas animations & gifs made easy.
JavaScript
13
star
35

next-ts-plugin-vscode

Always-on Next.js TypeScript Plugin in VSCode
TypeScript
11
star
36

blog

Next.js + MDX + ▲ ZEIT Now
JavaScript
9
star
37

innsbruck-old

A static blogging tool (to be reconstructed).
JavaScript
8
star
38

nextra-example

JavaScript
7
star
39

react-less-boilerplate

git clone [email protected]:quietshu/react-less-boilerplate.git
JavaScript
6
star
40

cube

Renderer written with JavaScript ES6 (Computer Graphics from the ground up)
JavaScript
6
star
41

list-label

The list with fixed labels.
JavaScript
6
star
42

raytracing

Ray Tracing Algorithm (光线追踪算法的实现和思考).
TeX
6
star
43

ghc

Lazy GitHub clone: navigate files in CLI without downloading the whole repo.
JavaScript
6
star
44

ABS-frontend

Another Bookstore System (-frontend), part of my homework of Database System Concepts course in Fudan CS. 这是个典型的 AngularJS+Bootstrap app.
JavaScript
6
star
45

siff17

2017 上海国际电影节完整排片数据
JavaScript
5
star
46

neon

用手机简易遥控浏览器(仿 Kinect 的体感操作……(据说很不稳定))
5
star
47

pingdash

A simple dashboard.
JavaScript
5
star
48

og-example

JavaScript
5
star
49

delay

alert(1); yield 1000; alert(2); // It works like MAGIC!
5
star
50

mak-old

(old repository) 坐等... ->
JavaScript
5
star
51

socket-chat-room

TCP socket programming...only homework, overwhelmed by homework.
JavaScript
5
star
52

13cs

13CS 院衫设计
CSS
4
star
53

-2048

Reverse 2048 with AI.
JavaScript
4
star
54

algorithm-contests

OI / ACM 代码记录
C++
4
star
55

leetcode-sol

弱。。。
JavaScript
4
star
56

shuffle-char

React char shuffling animation.
JavaScript
4
star
57

loading

Another CSS3 loading animation tool for full-page & blocks.
CSS
4
star
58

wishbottle

Mobile friendly version of stu.fudan.edu.cn/wish
JavaScript
4
star
59

textbook

🚧
JavaScript
3
star
60

awesome-frontend-charts

A curated list of awesome front-end visualization libraries (charts, maps, etc.), updating.
3
star
61

faster

(Unique Hack Day)
JavaScript
3
star
62

test-worker-transform-stream

JavaScript
3
star
63

wpjax

A PushState plugin for WordPress.
PHP
2
star
64

angel

🚧 constructing
JavaScript
2
star
65

.vim

My vim files.
C++
2
star
66

simple-hard-captcha

Simple but hard captcha for Node.js.
JavaScript
2
star
67

empty

i am empty
HTML
1
star
68

js-crawler-demo

A sample webpage crawler using node.js: asynchronous + jQuery
JavaScript
1
star
69

minutiae

[WIP] CSS-in-JS replacement for inline styles
TypeScript
1
star
70

innsbruck-plugins

JavaScript
1
star
71

class-sheet

A package that generates image from class-sheet data.
JavaScript
1
star
72

baidu-tieba-watcher

[Deprecated] 百度贴吧潜水员
Objective-C
1
star
73

excited-frontend

Frontend files for "EXCITED!"
CSS
1
star
74

fdu-hci-2016

Some experiments in human-computer interaction
HTML
1
star
75

mov

Some NLP stuff
JavaScript
1
star
76

dogesite

WOW, such doge!
JavaScript
1
star