hashcodeobject
v0.0.1
Published
This package is used to set `hashCode` property to a object.
Downloads
1
Readme
hashCodeObject
This package is used to set hashCode
property to a object.
Install
npm install --save hashcodeobject
Usage
import { defineDeepHashCodeObject } from 'hashcodeobject'
var obj = { a: { b: 10 } }
defineDeepHashCodeObject(obj)
console.log(obj.hashCode)
console.log(obj.a.hashCode)
API
getObjectHashCode(obj)
Get hash code from a given object/array.
import { getObjectHashCode } from 'hashcodeobject'
let hashCode = getObjectHashCode({ a: [ 1, 3, 4 ] })
defineObjectHashCodeProperty(obj)
Use defineProperty
to set a new property to the given object/array, so that you can use obj.hashCode
to get hash code.
Hash code is cached on obj._hashCodeCache
, the first time you call obj.hashCode
, caculation will be run, but the second time, cache will be used.
If you change a property of this object, cache will be clear, caculation will be run again the next time you call obj.hashCode
.
createHashCodeObject(obj)
defineObjectHashCodeProperty
listen to the top level properties, however, some objects have children in which there are objects too. For example:
var obj = {
x: 1,
children: {
y: 2,
},
}
This is not fit to use defineObjectHashCodeProperty
, it is better to use createHashCodeObject
.
import { createHashCodeObject } from 'hashcodeobject'
createHashCodeObject(obj)
obj.children.y = 3 // obj.hashCode changed
getComplexObjectHashCode(obj)
All of above methods do not support objects that has circle structure, i.e.
let a = { x: 1 }
let b = { y: 1, a }
a.b = b
Here a.b === b, and b.a === a, it is not possible to use JSON.stringify.
To resolve this problem, you'd better to use getComplexObjectHashCode
to get hash code here:
import { getComplexObjectHashCode } from 'hashcodeobject'
let hash = getComplexObjectHashCode(a)
console.log(hash)
However, it is not recommend to use circle structed object to caculate hash code. So I do not provide defineComplexHashCodeObject.