Détail du package

hash-it

planttheidea1.6mMIT6.0.0

Hash any object based on its value

hash, hashcode, object-hash, unique

readme

hash-it

Fast and consistent hashCode for any object type

Table of contents

Usage

// ES2015
import hash from 'hash-it';

// CommonJS
const hash = require('hash-it');

// hash any standard object
console.log(hash({ foo: 'bar' })); // 13729774857125

// or a circular object
console.log(hash(window)); // 3270731309314

Overview

hash-it has a simple goal: provide a fast, consistent, unique hashCode for any object type that is uniquely based on its values. This has a number of uses such as duplication prevention, equality comparisons, blockchain construction, etc.

Any object type?

Yes, any object type. Primitives, ES2015 classes like Symbol, DOM elements (yes, you can even hash the window object if you want). Any object type. Here is the list of object classes that produce consistent, unique hashes based on their value:

  • Arguments
  • Array
  • ArrayBuffer
  • AsyncFunction (based on toString)
  • AsyncGeneratorFunction (based on toString)
  • BigInt
  • BigInt64Array
  • BigUint64Array
  • Boolean
  • DataView (based on its buffer)
  • Date (based on getTime)
  • DocumentFragment (based on outerHTML of all children)
  • Error (based on stack)
    • Includes all sub-types (e.g., TypeError, ReferenceError, etc.)
  • Event (based on all properties other than Event.timeStamp)
    • Includes all sub-types (e.g., MouseEvent, KeyboardEvent, etc.)
  • Float32Array
  • Float64Array
  • Function (based on toString)
  • GeneratorFunction (based on toString)
  • Int8Array
  • Int16Array
  • Int32Array
  • HTMLElement (based on outerHTML)
    • Includes all sub-types (e.g., HTMLAnchorElement, HTMLDivElement, etc.)
  • Map (order-agnostic)
  • Null
  • Number
  • Object (handles circular objects, order-agnostic)
  • Proxy
  • RegExp
  • Set (order-agnostic)
  • SharedArrayBuffer
  • String
  • SVGElement (based on outerHTML)
    • Includes all sub-types (e.g., SVGRectElement, SVGPolygonElement, etc.)
  • Symbol (based on toString)
  • Uint8Array
  • Uint8ClampedArray
  • Uint16Array
  • Uint32Array
  • Undefined
  • Window

Are there any exceptions?

Sadly, yes, there are a few scenarios where internal values cannot be introspected for the object. In this case, the object is hashed based on its class type and reference.

  • Promise
    • There is no way to obtain the values contained within due to its asynchronous nature
  • Generator (the result of calling a GeneratorFunction)
    • Like Promise, there is no way to obtain the values contained within due to its dynamic iterable nature
  • WeakMap / WeakRef / WeakSet
    • The spec explicitly forbids iteration over them, so the unique values cannot be discovered
const promise = Promise.resolve(123);

console.log(hash(promise)); // 16843037491939
console.log(hash(promise)); // 16843037491939
console.log(hash(Promise.resolve(123))); // 4622327363876

If there is an object class or data type that is missing, please submit an issue.

Hash consistency

While the hashes will be consistent when calculated within the same environment, there is no guarantee that the resulting hash will be the same across different environments due to environment-specific or browser-specific implementations of features. This is limited to extreme edge cases, such as hashing the window object, but should be considered if being used with persistence over different environments.

Support

Browsers

  • Chrome (all versions)
  • Firefox (all versions)
  • Edge (all versions)
  • Opera 15+
  • IE 9+
  • Safari 6+
  • iOS 8+
  • Android 4+

Node

  • 4+

Development

Clone the repo and dependencies via yarn. The npm scripts available:

  • benchmark => run benchmark of various data types
  • benchmark:compare => run benchmark of some data types comparing against other hashing modules
  • build => run rollup to build ESM, CJS, and UMD files
  • clean => remove files produced from build script
  • dev => run webpack dev server to run example app / playground
  • lint => run ESLint against all files in the src folder
  • lint:fix => run lint script, automatically applying fixable changes
  • prepublishOnly => run typecheck, lint, test, and build
  • start => alias for dev script
  • test => run jest test functions with NODE_ENV=test
  • test:coverage => run test with coverage checker
  • test:watch => run test with persistent watcher
  • typecheck => run tsc to validate internal typings

changelog

hash-it CHANGELOG

6.0.0

Breaking changes

  • Equality utilities (is / is.any / is.all / is.not) are no longer provided
  • Error type hashes now include the message (previously only included stack)
  • Non-enumerable type hashes (Generator, Promise, WeakMap, WeakSet) now hash uniquely based on reference
  • WeakMap is now required at runtime (used as cache for circular references)

Enhancements

  • Better support for system-specific loading (ESM vs CJS vs UMD)
  • Added support for primitive wrappers (e.g. new Number('123'))
  • Added support for more object classes
    • AsyncFunction
    • AsyncGeneratorFunction
    • BigInt64Array
    • BigUint64Array
    • GeneratorFunction
    • SharedArrayBuffer
    • WeakRef (same limitations as those for WeakMap / WeakSet)

5.0.2

  • Reduce code size by 29.29% (19.42% gzipped size)
  • Activate strict mode for typing

5.0.1

  • Update .npmignore to reduce package tarball size (#39)

5.0.0

Breaking changes

  • Remove autocurrying of hash.is methods
  • Remove transpiled builds in favor of rollup distributed files (deep-linking will no longer work)

Enhancements

  • Codebase rewritten in TypeScript
  • Added BigInt support

4.1.0

  • Add TypeScript definitions
  • Significant speed improvements

4.0.5

  • Fix issues related to string encoding and collisions #23

4.0.4

  • Improve speed of complex objects (Objects, Arrays, Maps, Sets)
  • Fix security issue with old version of webpack-dev-server

4.0.3

  • Upgrade to use babel 7 for builds

4.0.2

  • Fix #18 - IE11 not allowing global toString to be used, instead using Object.prototype.toString (thanks @JorgenEvens)

4.0.1

  • Remove unused values from publish

4.0.0

Rewrite! Lots of changes under-the-hood for a much more consistent hash, and circular object handling out of the box.

BREAKING CHANGES

  • isEmpty, isEqual,isNull, and isUndefined have been removed (all can be reproduced with new is and is.all functions)
    • hash.isNull => hash.is(null)
    • hash.isUndefined => hash.is(undefined)
    • hash.isEqual => hash.is.all
    • hash.isEmpty => (object) => hash.is.any(object, undefined, null, '', 0, [], {}, new Map(), new Set())
  • Error hashes now based on error.stack instead of error.message

ENHANCEMENTS

  • Circular objects are now handled out of the box, thanks to fast-stringify
  • Collision rates are near-zero (previously used traditional DJB2, which has small collision rates)
  • Better ArrayBuffer support with the use of Buffer.from when supported
  • SVG elements, DocumentFragments, and Events are now supported
  • is partial-application function allows for easy creation of any type of isEqual comparison method
  • is.any performs the same multiple-object check that is.all does, but only checks if one of the other objects is equal
  • is.not performs the same comparison that is does, but checks for non-equality

FIXES

  • Object / Map / Set no longer returns different hashes based on order of key addition
  • hash.isEqual will no longer fail if nothing is passed

3.1.2

  • Remove extraneous toString call (performance)

3.1.1

  • Improve hash uniqueness for HTML elements

3.1.0

  • Add support for Generator (not just GeneratorFunction)
  • Streamline typeof- vs toString-driven handling for improved speed for most types

3.0.0

  • Improve speed (2-4x faster depending on type)
  • Smaller footprint (~25% reduction)
  • Improve hash accuracy for functions (hash now includes function body)
  • Fix issue where stack remained in memory after hash was built
  • Add ES transpilation for module-ready build tools

BREAKING CHANGES

  • If using CommonJS, you need to specify require('hash-it').default instead of just require('hash-it')
  • Hashes themselves may have changed (especially for circular objects)
  • Removed isRecursive method on hashIt object (which was wrongly named to begin with)
    • To specifically handle circular objects (which is what it really did), pass true as the second parameter to hashIt

2.1.2

  • Move up isNull check in replacer (improve performance of more likely use-case)

2.1.1

  • Create isNull utility instead of checking strict equality in multiple places

2.1.0

  • Overall speed improvement by an average of 18.74% (35.27% improvement on complex objects)

2.0.1

  • More speed improvements

2.0.0

  • Use JSON.stringify with replacer as default, without try/catch
  • Move use of try/catch with fallback to prune to new hashIt.withRecursion method (only necessary for deeply-recursive objects like window)
  • Reorder switch statement for commonality of use cases
  • Leverage typeof in switch statements when possible for performance

1.3.1

  • Add optimize-js plugin for performance in script version

1.3.0

  • Add hashIt.isUndefined, hashIt.isNull, and hashIt.isEmpty methods
  • Reorder switch statements in replacer and getValueForStringification to reflect most likely to least likely (improves performance a touch)
  • Remove "Number" from number stringification
  • Leverage prependTypeToString whereever possible
  • Include Arguments object class

1.2.1

  • Calculation of Math hashCode now uses properties
  • Fix README

1.2.0

  • Add hashIt.isEqual method to test for equality
  • Prepend all values not string or number with object class name to help avoid collision with equivalent string values

1.1.0

  • Add support for a variety of more object types
  • Fix replacer not using same stringifier for int arrays

1.0.0

  • Initial release