/**
* 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.
...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.