DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 28

The task is to implement a Node Store, which supports DOM elements as keys.

The boilerplate code

class NodeStore {
   /**
   * @param {Node} node
   * @param {any} value
   */
  set(node, value) {

  }
  /**
   * @param {Node} node
   * @return {any}
   */
  get(node) {

  }

  /**
   * @param {Node} node
   * @return {Boolean}
   */
  has(node) {

  }
}
Enter fullscreen mode Exit fullscreen mode

To use DOM elements as keys, we use a WeakMap. It is designed specifically for this kind of task because its key must be objects, and it automatically removes entries when the key object is no longer in memory, preventing memory leaks.

The first step is to initialize a new WeakMap to store mappings between nodes and values.

this._store = new WeakMap()
Enter fullscreen mode Exit fullscreen mode

The set method adds a new entry to the store. It takes the DOM node and any other value and saves the mapping in the WeakMap.

set(node, value) {
   this._store.set(node, value)
  }
Enter fullscreen mode Exit fullscreen mode

The get method retrieves the value associated with a given node

get(node) {
    return this._store.get(node)
  }
Enter fullscreen mode Exit fullscreen mode

The has method checks whether a particular node exists as a key in the store

has(node) {
   return this._store.has(node)
  }
Enter fullscreen mode Exit fullscreen mode

There's no need to check for invalid inputs because WeakMap automatically adds that.

The final code is:

class NodeStore {
   constructor() {
    this._store = new WeakMap()
   }
  set(node, value) {
   this._store.set(node, value)
  }
  get(node) {
    return this._store.get(node)
  }
  has(node) {
   return this._store.has(node)
  }
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)