Converting objects to hash signatures in JavaScript
kuby.ca
kuby.ca
Better collision properties, easier to implement, and a cryptographic hash to boot, just as long as you don’t have circular references and only care about the serializable “contents” of an object.
In addition, the containers need to have these same comparators, so all your data structures will need to be wrapped or redefined (arrays, hashmaps, etc).
It's much harder than it appears on the surface. You may get cases of infinite recursion in cases of mutual references. For a quick and dirty comparison, you can convert both objects to JSON and compare those strings. In fact the JSON string, if made to be deterministic, can exactly fulfill this function of this "hash" which is used to compare two objects.
Even a basic comparison between two nested arrays is work in JS, so we need articles like this for things we use day to day. It's weird that the orgs building the standard think that a common promise API is a priority, but a decent namespace system or a way to manipulate builtin datastructures without 3rd party lib isn't.
I seem to remember the early days of Java where hashCode for string only looked at the first few characters - which had amusing results when storing URLs.
Browser:
const crypto = window.crypto || window.msCrypto; // IE11
return window.crypto.subtle.digest('SHA-256', stableStringify(obj));
Node: require('crypto')
.createHash('sha256')
.update(pwd)
.digest('base64');
[1] https://www.npmjs.com/package/json-stable-stringifyIt would be simpler, faster, and more correct (no chance of collisions) to just implement an isEqual method.
That said, why are we doing this and where is our native isEqual method?