A deterministic object hashing algorithm for Node.js

Overview

Deterministic-Object-Hash

A deterministic object hashing algorithm for Node.js.

The Problem

Using JSON.stringify on two objects that are deeply equal does not lead to the same output string. Instead the keys are ordered in the same order that they were added. This leads to two objects that are deeply equal being hashed to different values.

= {}; obj1['a'] = 'x'; obj1['b'] = 'y'; obj1['c'] = 'z'; const obj2: Record = {}; obj2['c'] = 'z'; obj2['b'] = 'y'; obj2['a'] = 'x'; isEqual(obj1, obj2); // -> true const string1 = JSON.stringify(obj1); // -> {"a":"x","b":"y","c":"z"} const string2 = JSON.stringify(obj2); // -> {"c":"z","b":"y","a":"x"} createHash('sha1').update(string1).digest('hex'); // -> ff75fe071d236ce309c15d5636ecaa86c0519ebc createHash('sha1').update(string2).digest('hex'); // -> 2e53bac865f7be77c8e10cd86d737fbbf259ed37">
import { createHash } from "crypto";
import { isEqual } from "lodash";

const obj1: Record<string, string> = {};
obj1['a'] = 'x';
obj1['b'] = 'y';
obj1['c'] = 'z';

const obj2: Record<string, string> = {};
obj2['c'] = 'z';
obj2['b'] = 'y';
obj2['a'] = 'x';

isEqual(obj1, obj2);
// -> true

const string1 = JSON.stringify(obj1);
// -> {"a":"x","b":"y","c":"z"}
const string2 = JSON.stringify(obj2);
// -> {"c":"z","b":"y","a":"x"}

createHash('sha1').update(string1).digest('hex');
// -> ff75fe071d236ce309c15d5636ecaa86c0519ebc
createHash('sha1').update(string2).digest('hex');
// -> 2e53bac865f7be77c8e10cd86d737fbbf259ed37

Usage

Pass any Javascript value and receive a deterministic hash of the value. If an object is passed, only own enumerable string-keyed properties are used.

import deterministicHash from 'deterministic-object-hash';

const objA = { a: 'x', arr: [1,2,3,4], b: 'y' };
const objB = { b: 'y', a: 'x', arr: [1,2,3,4] };

deterministicHash({
	c: [ objA, objB ],
	b: objA,
	e: objB,
	f: ()=>{ Math.random(); },
	g: Symbol('Unique identity'),
	h: new Error('AHHH')
});
// -> 455b32a99a84efad551409b39bd91fc028a98343

deterministicHash({
	h: new Error('AHHH'),
	e: objB,
	g: Symbol('Unique identity'),
	b: objA,
	f: ()=>{ Math.random(); },
	c: [ objA, objB ]
});
// -> 455b32a99a84efad551409b39bd91fc028a98343

Settings

A hash algorithm can be passed as the second argument. This takes any value that is valid for crypto.createHash. The default is sha1.
A digest format can be passed as the third argument. This takes any value that is valid for Hash.digest. The default is hex.

deterministicHash('value', 'sha1');
// -> f32b67c7e26342af42efabc674d441dca0a281c5
deterministicHash('value', 'sha256', 'hex');
// -> cd42404d52ad55ccfa9aca4adc828aa5800ad9d385a0671fbcbf724118320619
deterministicHash('value', 'sha512', 'base64');
// -> 7CyD7ey2AwTRVOvbhb369hqSvRQuccT3sloVuctfPArjAc+zVpzyQORHADE4U0i8KW2NmdCeBrJvCVkal1Jylg==

Support

Currently this has only been tested on Node.js 16.3.x. More tests are to come and this section will be updated as I test them.

You might also like...

Dominating set solver using quantum algorithm Grover

Solution for dominating set problem using improved quantum algorithm Grover, which uses Schoning algorithm for k-SAT problem to accomplish this improvement

Aug 31, 2022

Non-interactive publicly verifiable distributed key generation and resharing algorithm over BLS12-381

NPVDKG-RS This repository contains a mathematical presentation and some code to demonstrate our developed non-interactive publicly verifiable distribu

May 19, 2022

🤖A Tic-Tac-Toe solver that uses the minimax algorithm and alpha-beta pruning to make it unbeatable

🤖A Tic-Tac-Toe solver that uses the minimax algorithm and alpha-beta pruning to make it unbeatable

Tic-Tac-Toe AI A Tic-Tac-Toe solver that uses the minimax algorithm and alpha-beta pruning to make it unbeatable How it Works Tic-Tac-Toe is what is k

May 20, 2022

Fast and robust triangle-triangle intersection test with high precision for cross and coplanar triangles based on the algorithm by Devillers & Guigue.

fast-triangle-triangle-intersection Fast and robust triangle-triangle intersection test with high precision for cross and coplanar triangles based on

Nov 15, 2022

⭐️ my baekjoon algorithm

Baekjoon Algorithm Python3 import sys # 공백으로 구분된 2개 숫자 입력 받기 N, M = map(int, sys.stdin.readline().split()) # 여러 줄 입력 받기 n = int(sys.stdin.readline

Jul 22, 2022

k-means algorithm module for n-dimensional data

K-Means Algorithm This module allows you to compute the k-Means algorithm with n-dimensional data. You simply put in your data as a list and the k you

Jan 31, 2022

This project will be using various AI and Rule Engine algorithm to detect various attack against a company!

This project will be using various AI and Rule Engine algorithm to detect various attack against a company!

📌 Introduction This project will be using various AI and Rule Engine algorithm to detect various attack against a website! 📌 Mission After starting

Apr 29, 2022

A Flood-Fill Algorithm written in JavaScript

flood https://magnogen.net/flood A Flood-Fill Algorithm for Creative Coders This is the source code for a section of my website. You're welcome to sno

Dec 22, 2022

Deno's first lightweight, secure distributed lock manager utilizing the Redlock algorithm

Deno-Redlock Description This is an implementation of the Redlock algorithm in Deno. It is a secure, lightweight solution to control resource access i

Dec 31, 2022
Owner
Zane Bauman
Web technology lover. Obsessed with Redis. Always working on a project.
Zane Bauman
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
Generate deterministic fake values: The same input will always generate the same fake-output.

import { copycat } from '@snaplet/copycat' copycat.email('foo') // => '[email protected]' copycat.email('bar') // => 'Thurman.Schowalter668@

Snaplet 201 Dec 30, 2022
Minimal implementation of SLIP-0010 hierarchical deterministic (HD) wallets

micro-ed25519-hdkey Secure, minimal implementation of SLIP-0010 hierarchical deterministic (HD) wallets. Uses audited @noble/ed25519 under the hood. B

Paul Miller 11 Dec 25, 2022
Types generator will help user to create TS types from JSON. Just paste your single object JSON the Types generator will auto-generate the interfaces for you. You can give a name for the root object

Types generator Types generator is a utility tool that will help User to create TS Interfaces from JSON. All you have to do is paste your single objec

Vineeth.TR 16 Dec 6, 2022
A personal semantic search engine capable of surfacing relevant bookmarks, journal entries, notes, blogs, contacts, and more, built on an efficient document embedding algorithm and Monocle's personal search index.

Revery ?? Revery is a semantic search engine that operates on my Monocle search index. While Revery lets me search through the same database of tens o

Linus Lee 215 Dec 30, 2022
Algorithm visualizer made with React, Material UI and P5JS.

Made with React, P5JS and Material UI. Link https://andresrodriguez55.github.io/algorithmsVisualizer/#/ Description The purpose of doing this was to l

Andres Arturo Rodriguez Calderon 31 Nov 22, 2022
JS_GAME/Algorithm

?? JS_GAME JavaScript 를 이용하여 각종 게임을 만들어보자. (자바스크립트를 사용해서 게임을 만들 수 있음.) 웹페이지를 만드는 것도 좋지만, JS 를 이용하여 간단한 게임을 만들면서 생각의 전환을 해보자. 클론 코딩도 좋다! 하지만, 클론 코딩 후에

LEEJAE-GO 2 Nov 5, 2021
NodeJS Implementation of Decision Tree using ID3 Algorithm

Decision Tree for Node.js This Node.js module implements a Decision Tree using the ID3 Algorithm Installation npm install decision-tree Usage Import

Ankit Kuwadekar 204 Dec 12, 2022