Skip to content

Instantly share code, notes, and snippets.

@james4388
Created January 8, 2020 06:26
Show Gist options
  • Save james4388/95600b551ebd44a16fe9ce361f66185e to your computer and use it in GitHub Desktop.
Save james4388/95600b551ebd44a16fe9ce361f66185e to your computer and use it in GitHub Desktop.
Map like structure that can has key is an object or DOM Node.
/* Using array to store and search for key. Time complexity O(n) */
class DOMStoreArray {
constructor () {
this.data = [];
}
find (node) {
for (let item of this.data) {
if (item[0] === node) {
return item;
}
}
return null;
}
has (node) {
return this.find(node) !== null;
}
set (node, value) {
const item = this.find(node);
if (item) {
item[1] = value;
return;
}
this.data.push([node, value]);
}
get (node, defaultValue) {
const item = this.find(node);
if (item) {
return item[1];
}
return defaultValue;
}
}
/* Cheating, store data directly on object O(1)*/
class DOMStore {
constructor () {
this.DOMStoreSymbol = Symbol('DOMStore');
}
has (node) {
return node[this.DOMStoreSymbol] !== undefined;
}
set (node, value) {
node[this.DOMStoreSymbol] = value;
}
get (node, defaultValue) {
return node[this.DOMStoreSymbol] || defaultValue;
}
}
/* Test */
const e1 = document.createElement('A');
const e2 = document.createElement('P');
const e3 = document.createElement('DIV');
const e4 = document.createElement('TABLE');
const e5 = document.createElement('A');
const map1 = new DOMStore();
const map2 = new DOMStore();
console.assert(map1.has(e1) === false, 'map1 should be empty');
map1.set(e1, 'E1 in map1');
console.assert(map1.has(e1) === true, 'map1 must have e1');
map2.has(e1);
console.assert(map2.has(e1) === false, 'map2 should be empty');
map1.set(e2, 1234);
map1.set(e3, "String");
map1.set(e4, [1,2,3,4]);
console.assert(map1.get(e5, null) === null);
console.assert(map1.get(e5) === undefined);
console.assert(map1.get(e5, 5) === 5);
map1.set(e5, {1: 2, 3: 4});
console.assert(map1.get(e1) === 'E1 in map1');
console.assert(typeof(map1.get(e5)) === 'object');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment