DOMStore

facebook

by Paco86

HTML

<!-- 
Create a DOM Store so that it has 3 methods: set, get and has
DOM Store should be able to store a DOM Node and return the value associated with particular Node.


var span = document.getElementById('hello');
var store = new DOMStore();

store.set(span, 1);
store.get(span); // 1
store.has(span); //true
store.set(span, 2); //update span to 2
store.get(span); //2

Note: the DOMStore should store the reference of DOM as the key and not the id;  -->

<span></span>
<span></span>

JavaScript

class DOMStore {

  constructor() {
    this.map = {};
    this.storeId = 1;
  }
  
  set = (node, value) => {
    const storeId = node.getAttribute('storeId');
    // add storeId
    if (!storeId) {
      node.setAttribute('storeId', this.storeId);
      this.map[this.storeId] = {
        node, value
      };
      this.storeId += 1;
    } else {
    	//update storeId
    	this.map[storeId] = { node, value };
    }
  };
  
  get = (node) => {
    const storeId = node.getAttribute('storeId');
    if (storeId) {
      return this.map[parseInt(storeId)].value;
    }
    return null;
  };
  
  has = (node) => {
    return node.hasAttribute('storeId');
  }
}

class DOMStore2 {
	constructor() {
  	this.keys = [];
    this.values = []
  }
  
  set = (node, value) => {
  	const index = this.keys.indexOf(node);
		if (index > -1) {
    	this.values[index] = value;
    } else {
    	this.keys.push(node);
    	this.values.push(value);
    }
  };
  
  get = (node) => {
    const index = this.keys.indexOf(node);
    return index > -1 ? this.values[index] : null;
  };
  
  has = (node) => {
    return this.keys.indexOf(node) > -1;
  }
}


class DOMStore3 {
	constructor() {
  	this.domProp = Symbol();
  }
  
  set = (node, value) => {
  	node[this.domProp] = value;
  };
  
  get = (node) => {
    return node[this.domProp];
  };
  
  has = (node) => {
    return !!this.get(node);
  }
  
}


class DOMStore4 {
	constructor() {
  	this.map = new Map();
  }
  
  set = (node, value) => {
  	this.map.set(node, value);
  };
  
  get = (node) => {
  	return this.map.get(node);
  };
  
  has = (node) => {
  	return this.map.has(node);
  }
}

class DOMStore5 {
  set(element, value) {
  	element._storeValue = value;
  }
  
  get(element) {
  	return element._storeValue;
  }
  
  has(element) {
  	return element.hasOwnProperty('_storeValue');
  }
}


var span1 = document.getElementsByTagName('span')[0];
var span2 = document.getElementsByTagName('span')[1];
var store = new...