Skip to content

Instantly share code, notes, and snippets.

@Olical
Created June 11, 2013 19:42
Show Gist options
  • Save Olical/5759960 to your computer and use it in GitHub Desktop.
Save Olical/5759960 to your computer and use it in GitHub Desktop.
A JavaScript map implementation. Will be on my blog soon: http://oli.me.uk/
/**
* A simple map implementation. Uses two arrays to store the keys and values as well as indexOf to search through them.
*
* You could swap indexOf for a binary search if you need more speed: http://oli.me.uk/2013/06/08/searching-javascript-arrays-with-a-binary-search/
*
* @class
*/
function Map() {
this._createStorage();
}
/**
* Assigns a vale to a key. Will override a value if you use the same key twice.
*
* @param {*} key
* @param {*} value
* @return {Object} Current map instance to allow chaining.
*/
Map.prototype.set = function (key, value) {
var index = this._getIndexOf(key);
this._keys[index] = key;
this._values[index] = value;
return this;
};
/**
* Fetch a value which has already been assigned to the specified key.
*
* @param {*} key
* @return {*} The value that was assigned to the key, if any.
*/
Map.prototype.get = function (key) {
var index = this._getIndexOf(key);
return this._values[index];
};
/**
* Removes the value from the map that was assigned to the provided key.
*
* @param {*} key
* @return {Object} Current map instance to allow chaining.
*/
Map.prototype.remove = function (key) {
var index = this._getIndexOf(key);
if (index !== this._keys.length) {
this._keys.splice(index, 1);
this._values.splice(index, 1);
}
return this;
};
/**
* Wipes the whole map objects storage. The same as calling `remove` on each value, one by one.
*
* @return {Object} Current map instance to allow chaining.
*/
Map.prototype.clear = function () {
this._createStorage();
return this;
};
/**
* Creates the storage arrays to be used internally.
*
* @return {Object} Current map instance to allow chaining.
* @private
*/
Map.prototype._createStorage = function () {
this._keys = [];
this._values = [];
};
/**
* Fetches the index of the provided key. If a matching key can't be found, it returns where you should inject that value within the storage array.
*
* @param {*} key
* @return {Object} Current map instance to allow chaining.
* @private
*/
Map.prototype._getIndexOf = function (key) {
var index = this._keys.indexOf(key);
return index === -1 ? this._keys.length : index;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment