To store DOM Elements as keys in object without using WeakMap( ), we can do the following:
<div id="root"></div>
<script>
class NodeStore {
static key = 'key';
set(node, value) {
node.dataset[NodeStore.key] = value;
}
get(node) {
return this.has(node) && node.dataset[NodeStore.key];
}
has(node) {
return NodeStore.key in (node?.dataset || {});
}
}
const nodeStore = new NodeStore();
const root = document.getElementById('root');
nodeStore.set(root, 'root value');
console.log(nodeStore.has(root)); // true
console.log(nodeStore.get(root)); // 'root value'
</script>
However the above solution can only support values of type string. To support any type of value we can use the following solution:
<div id="root"></div>
<script>
class NodeStore {
static key = 'key';
constructor() {
this.map = {};
this.counter = 0;
}
/**
* @param {Node} node
* @param {any} value
*/
set(node, value) {
node[NodeStore.key] = this.counter;
this.map[this.counter++] = value;
}
/**
* @param {Node} node
* @return {any}
*/
get(node) {
if (this.has(node)) {
return this.map[node[NodeStore.key]];
}
return;
}
/**
* @param {Node} node
* @return {Boolean}
*/
has(node) {
return NodeStore.key in node;
}
}
const nodeStore = new NodeStore();
const root = document.getElementById('root');
nodeStore.set(root, 22);
console.log(nodeStore.has(root)); // true
console.log(nodeStore.get(root)); // 22
</script>