Created
June 2, 2020 21:21
-
-
Save g4rcez/6f8a57c8170f7cb5b52a41285aeaca5a to your computer and use it in GitHub Desktop.
This file contains hidden or 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
export const equals = (a: any, b: any): boolean => { | |
if (a === b) { | |
return true; | |
} | |
if (a instanceof Date && b instanceof Date) { | |
return a.getTime() === b.getTime(); | |
} | |
if (!a || !b || (typeof a !== "object" && typeof b !== "object")) { | |
return a === b; | |
} | |
if (a.prototype !== b.prototype) { | |
return false; | |
} | |
const keys = Object.keys(a); | |
if (keys.length !== Object.keys(b).length) { | |
return false; | |
} | |
return keys.every((k) => equals(a[k], b[k])); | |
}; | |
export default class ObjectMap<K extends object, V> extends WeakMap<K, V> { | |
private map: Map<K, V>; | |
public [Symbol.toStringTag]: string; | |
public constructor() { | |
super(); | |
this.map = new Map<K, V>(); | |
} | |
public delete(key: K): boolean { | |
const k = this.key(key); | |
return this.map.delete(k); | |
} | |
private key(key: K): K { | |
return [...this.map.keys()].find((x) => equals(x, key)) as any; | |
} | |
public get(key: K): V | undefined { | |
const k = this.key(key); | |
if (!!k) { | |
return this.map.get(k); | |
} | |
} | |
public set(key: K, val: V) { | |
this.map.set(key, val); | |
return this; | |
} | |
public has(key: K): boolean { | |
const k = this.key(key); | |
return this.map.has(k); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment