Created
November 17, 2020 16:57
-
-
Save ianliu/4c7ac3b176255e86fb42c4f065eab657 to your computer and use it in GitHub Desktop.
Simple dictionary with value equality for keys
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Recursive object key sort for predictable JSON serialization | |
*/ | |
function sortObject(obj) { | |
if (!obj || typeof obj !== "object") return obj; | |
if (Array.isArray(obj)) return obj.map(item => sortObject(item)); | |
return Object.keys(obj).sort().reduce((o, x) => (o[x] = sortObject(obj[x]), o), {}); | |
} | |
/** | |
* Predictable JSON serialization of an object | |
*/ | |
function hash(obj) { return JSON.stringify(sortObject(obj)); } | |
/** | |
* Simple class that wraps a Map with key serialization/deserialization | |
*/ | |
class Dict { | |
constructor() { this._map = new Map(); } | |
get length() { return this._map.length; } | |
has(key) { return this._map.has(hash(key)); } | |
get(key) { return this._map.get(hash(key)); } | |
set(key, val) { this._map.set(hash(key), val); } | |
*[Symbol.iterator]() { | |
for (let [key, val] of this._map) | |
yield [JSON.parse(key), val]; | |
} | |
} | |
/* Examples */ | |
const d = new Dict(); | |
d.set({ foo: 10 }, "Hi!"); | |
d.get({ foo: 10 }); // Returns "Hi!" | |
for (const [k, v] of d) { | |
// "k" is an object { foo: 10 } | |
// "v" is "Hi!" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment