https://bigfrontend.dev/problem/create-a-simple-store-for-DOM-node
We have Map
in es6, so we could use any data as key, such as DOM element.
const map = new Map();
map.set(domNode, somedata);
What if we need to support old JavaScript env like es5, how would you create your own Node Store as above?
You are asked to implement a Node Store, which supports DOM element as key.
class NodeStore {
set(node, value) {}
get(node) {}
has(node) {}
}
note
Map
is disabled when judging your code, it is against the goal of practicing.
You can create a simple general Map
polyfill. Or since you are asked to support specially for DOM element, what is special about DOM element?
What is the Time / Space cost of your solution?
class NodeStore {
constructor() {
this.nodes = {};
}
/**
* @param {Node} node
* @param {any} value
*/
set(node, value) {
node.__id__ = Symbol();
this.nodes[node.__id__] = value;
}
/**
* @param {Node} node
* @return {any}
*/
get(node) {
return this.nodes[node.__id__];
}
/**
* @param {Node} node
* @return {Boolean}
*/
has(node) {
// coerce to boolean value
return !!this.nodes[node.__id__];
}
}
const store = new NodeStore();
const Node = function () {};
const node1 = new Node();
const node2 = new Node();
store.set(node1, "foo");
store.set(node2, "bar");
console.log(store.get(node1)); // 'foo'
console.log(store.get(node2)); // 'bar'
console.log(store.has(node1)); // true
console.log(store.has(node2)); // true
console.log(store.has(new Node())); // false
Let's break down the NodeStore
class and its usage:
-
Class Definition: The
NodeStore
class is defined with a constructor and three methods:set
,get
, andhas
. -
Constructor: The constructor initializes an empty object
this.nodes
that will be used to store nodes. -
set
Method: This method takes anode
and avalue
as parameters. It assigns a unique identifier to thenode
usingSymbol()
and then stores thevalue
inthis.nodes
using the unique identifier as the key. -
get
Method: This method takes anode
as a parameter and returns the value associated with thenode
fromthis.nodes
. -
has
Method: This method takes anode
as a parameter and checks ifthis.nodes
has a value for thenode
. It returns a boolean value. -
Usage: The usage example shows how to use the
NodeStore
class. It creates a newNodeStore
instance and two newNode
instances. It uses theset
method to store values for the nodes, theget
method to retrieve the stored values, and thehas
method to check if values are stored for the nodes.
This NodeStore
class provides a way to associate values with nodes in a way that doesn't mutate the nodes themselves (except for adding a unique identifier). This can be useful in situations where you need to store metadata about nodes, for example in a graph or tree data structure.