3.0.0 • Published 2 years ago

node-object-hash v3.0.0

Weekly downloads
1,051,676
License
MIT
Repository
github
Last release
2 years ago

node-object-hash

Tiny and fast node.js object hash library with properties/arrays sorting to provide constant hashes. It also provides a method that returns sorted object strings that can be used for object comparison without hashes. One of the fastest among other analogues (see benchmarks).

Hashes are built on top of node's crypto module. If you want to use it in browser it's recommented to use objectSorter only. It will provide you with unique string representation of your object. Afterwards you may use some hash library to reduce string size. Also you may use something like browserify-crypto or some kind of crypto functions polyfills.

Node NPM Version Downloads Count Vunerabilities Count Npms.io Score Build Status License Codecov Coverage

ToC

What's new in v3.0.0

Disclaimer: No new features or changes that may break hashes from previous versions. There's no need to update unless you're starting project from scratch.

  • Refactor and migration to typescript 5.
  • Drop old node support.
  • Removed typescript namespaces.
  • Updated exported functions and object structure.
  • Removed faker and old benchmarks.
  • New CI and release automation.

What's new in v2.0.0

Breaking changes

  • Library rewritten in typescript that could cause some side-effects, but it should not.
  • With coerce=false Sets will no longer generate the same hashes as Arrays. In order to restore previous behavior set coerce.set=true.
  • With coerce=false Symbols will generate hash based on symbol .toString value. That's useful for Symbol.for('smth'). If coerce.symbol=true all Symbolss will have equal hashes. TLDR; If you use library with Sets or Symbols with coerce=false in order to keep hashes the same as in v1.X.X you should use following constructor:
const hasher = require('node-object-hash')({coerce: {set: true, symbol: true}})
  • Object sorter sources moved to dist directory. If you required it directly via require('node-object-hash/objectSorter') you should change it to require('node-object-hash/dist/objectSorter').
  • Removed old v0 version from code.
  • Changed license to MIT.

New features

  • New granular options. Now you can specify what types need to be sorted or coerced.
  • Add new trim option. It can be used to remove unncecessary spaces in strings or function bodies.
  • Library rewritten to typescript, so it may have better ts compatibility.

Installation

npm i node-object-hash -S

Features

  • Supports object property sorting for constant hashes for objects with same properties, but different order.
  • Supports ES6 Maps and Sets.
  • Supports type coercion (see table below).
  • Supports all hashes and encodings of crypto library.
  • Supports large objects and arrays.
  • Has granular options that allows to control what should be sorted or coerced.
  • Very fast comparing to other libs (see Benchmarks section).

Type map

This map displays what types will have identical string representation (e.g. new Set(1, 2, 3) and 1, 2, 3 will have equal string representations and hashes.

Initial typeMapped type
Array ([])array
ArrayObject (new Array())
Int8Array
Uint8Array
Uint8ClampedArray
Int16Array
Uint16Array
Int32Array
Uint32Array
Float32Array
Float64Array
Buffer
Set
Maparrayarray
string ('')string
String (new String())
boolean (true)boolean
Boolean (new Boolean())
number (true)number
Number (new Number())
Datedate
Symbolsymbol
undefinedundefined
nullnull
functionfunction
Object ({})object
Object (new Object())
otherunknown

Coercion map

Initial "type"Coerced typeExample
booleanstringtrue -> 1
numberstring'1' -> 1
stringstring'a' -> a
nullstring (empty)null ->
undefinedstring (empty)undefined ->

Changes

See changelog For v2 changes see changelog-v2

Docs

Full API docs could be found in docs.

API overview

Constructor

require('node-object-hash').hasher([options]);

Returns preconfigured object with API

Parameters:

  • options:object - object with hasher config options
  • options.coerce:boolean|object - if true performs type coercion (default: true); e.g. hash(true) == hash('1') == hash(1), hash(false) == hash('0') == hash(0)
  • options.sort:boolean|object - if true performs sorting on objects, arrays, etc. (default: true); in order to perform sorting on TypedArray (Buffer, Int8Array, etc.), specify it explicitly: typedArray: true
  • options.trim:boolean|object - if true performs trim of spaces and replaces space-like characters with single space (default: false);
  • options.alg:string - sets default hash algorithm (default: 'sha256'); can be overridden in hash method;
  • options.enc:string - sets default hash encoding (default: 'hex'); can be overridden in hash method;

API methods

hash(object[, options])

Returns hash string.

  • object:* object for calculating hash;
  • options:object object with options;
  • options.alg:string - hash algorithm (default: 'sha256');
  • options.enc:string - hash encoding (default: 'hex');

sort(object)

Returns sorted string generated from object (can be used for object comparison)

  • object:* - object for sorting;

Hashing custom objects

In order to serialize and hash your custom objects you may provide .toHashableString() method for your object. It should return string that will be hashed. You may use objectSorter and pass notable fields to it in your .toHashableString method.

For typescript users you may add to your classes implements Hashable.

Requirements

version >=1.0.0

  • >=nodejs-0.10.0

version >=0.1.0 && <1.0.0

  • >=nodejs-6.0.0
  • >=nodejs-4.0.0 (requires to run node with --harmony flag)

Examples

var { hasher } = require('node-object-hash');

var hashSortCoerce = hasher({ sort: true, coerce: true });
// or
// var hashSortCoerce = hasher();
// or
// var hashSort = hasher({sort:true, coerce:false});
// or
// var hashCoerce = hasher({sort:false, coerce:true});

var objects = {
  a: {
    a: [{ c: 2, a: 1, b: { a: 3, c: 2, b: 0 } }],
    b: [1, 'a', {}, null],
  },
  b: {
    b: ['a', 1, {}, undefined],
    a: [{ c: '2', b: { b: false, c: 2, a: '3' }, a: true }],
  },
  c: ['4', true, 0, 2, 3],
};

hashSortCoerce.hash(objects.a) === hashSortCoerce.hash(objects.b);
// returns true

hashSortCoerce.sort(object.c);
// returns '[0,1,2,3,4]'

For more examples you can see tests or try it out online at runkit

Benchmarks

Bench data - array of 100000 complex objects

Usage

  • npm run bench to run custom benchmark
  • npm run benchmark to run benchmark suite
  • npm run benchmark:hash to run hash benchmark suite

Results

Hashing algorithmResult hash bytes lengthPerformance (ops/sec)
sha256 (default)641,599 +- 5.77%
sha1401,983 +- 1.50%
sha224561,701 +- 2.81%
sha384961,800 +- 0.81%
sha5121281,847 +- 1.75%
md4321,971 +- 0.98%
md5321,691 +- 3.18%
whirlpool1281,487 +- 2.33%

Custom benchmark (code)

LibraryTime (ms)Memory (Mb)
node-object-hash-0.2.15813.57534
node-object-hash-1.0.X2805.58127
node-object-hash-1.1.X (node v7)2555.58327
node-object-hash-1.2.X (node v7)2390.75228
node-object-hash-2.X.X (node v12)1990.62224
object-hash-1.1.5 (node v7)28115.55339
object-hash-1.1.4534528.25441
object-hash-1.1.3ERROROut of heap memory
hash-object-0.1.79219.82642

Benchmark suite module (code)

Library (node v12)Perf (ops/s)
node-object-hash-2.0.02087 ±0.59%
object-hash-1.3.1239 ±0.39%
hash-object-0.1.7711 ±0.18%

Links

  • object-hash - Slow, useful for browsers because it not uses node's crypto library
  • hash-object - no ES6 types support

License

MIT

@apecommerce/ape-framework@nhatle/react-build-tools@mtgroup/jest-webpack@nghiepuit/sdk-builderbase-sdk-buildernghiepuit-build-tools@nghiepuit/react-build-tool@parade/utilsdisposabletestabcdtransaction-service@microeinhundert/radonis-manifestseqredis@everything-registry/sub-chunk-2307ezs-boosterezs-lodexwongterrencew-fork-phenomicweave-coreshield-resourcessewing-kit-betasewing-kit-of-lemonssewing-kittensewing-websewing-kitsewing-web-testservicerrearguardremzyvite-plugin-build-idvue-cli-plugin-fasterlms-react-sdklayerizegraphql-tools-subscribegraphql-io-serverjest-webpackinterbit-test-harnessinterbit-corekadrehard-source-webpack-pluginhard-source-webpack-plugin-fixed-hashbughard-source-webpack-plugin-patchmongoriteplasmoomg-rc-cliproductivity-timernode-async-decoratorsnice-swapiphenomicphenonexphenomic-for-nexarphenomic-serverlessnetlify-minutesreddinxspritesheet-gamestrapi-sharprxjstoresiyahsorrir-frameworktm-hard-source-webpack-plugints-openapi@archmagelive/plasmo@apployees-nx/node@apployees-nx/webserver@all3dp/material-structure@axa/bautajs-decorator-cache@axa/native-proxy-agent@bloomreach/frontend-build@bluelibs/x-bundle@azure/avocado@diablohu/hard-source-webpack-plugin@data-leakage-protection/signatureszigniswebpack-mixeruse-hashed-statevc-webpack-vendors@hsiwe/schema-types-generator@eldarlabs/phenomic@elrondnetwork/attest.core@elrondnetwork/attest@elrondnetwork/evertrail.core@goodforonefare/sewing-kit@goodforonefare/sewing-kitten@etomon/encode-tools@infinitebrahmanuniverse/nolb-node-o@lmagder/node-stable-diffusion-cpp@leshak/micro-app@leetcode/hard-source-webpack-plugin@isoreact/core@mostlyserious/brightpack@muta-extra/knex-mysql@mathieudutour/plasmo@netlify/content-engine@newsteam/brick@nghiepuit/react-sdk@mzgoddard/jest-webpack@naiverlabs/tskit@ezs/analytics@ezs/booster@ezs/core@ezs/lodex@minar-kotonoha/hard-source-webpack-plugin
3.0.0

2 years ago

2.3.10

3 years ago

2.3.9

3 years ago

2.3.8

3 years ago

2.3.6

4 years ago

2.3.5

4 years ago

2.3.7

4 years ago

2.3.4

4 years ago

2.3.2

4 years ago

2.3.3

4 years ago

2.3.1

4 years ago

2.3.0

4 years ago

2.2.0

4 years ago

2.1.2

4 years ago

2.1.0

4 years ago

2.0.0

5 years ago

2.0.0-rc.1

5 years ago

1.4.2

6 years ago

1.4.1

7 years ago

1.4.0

7 years ago

1.3.0

7 years ago

1.2.0

8 years ago

1.1.6

8 years ago

1.1.5

8 years ago

1.1.4

8 years ago

1.1.3

8 years ago

1.1.2

8 years ago

1.1.1

8 years ago

1.1.0

8 years ago

1.0.3

8 years ago

1.0.2

8 years ago

1.0.1

8 years ago

1.0.0

8 years ago

0.2.1

8 years ago

0.2.0

8 years ago

0.1.1

8 years ago

0.1.0

8 years ago