Skip to content

Instantly share code, notes, and snippets.

@nodirt
Created December 12, 2011 23:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nodirt/1469647 to your computer and use it in GitHub Desktop.
Save nodirt/1469647 to your computer and use it in GitHub Desktop.
Indexers in JavaScript
function FakeMap() {
var data = [];
function indexOf(key) {
var i;
for (i = 0; i < data.length; i++) {
if (data[i].key === key) return i;
}
return -1;
}
function find(key) {
var index = indexOf(key);
return index < 0 ? null : data[index];
}
// the indexer
function indexer(key, value) {
var entry = find(key);
if (arguments.length == 2) {
if (entry) {
entry.value = value;
} else {
entry = { key: key, value: value };
data.push(entry);
}
}
return entry.value;
}
indexer.remove = function (key) {
var index = indexOf(key);
if (index < 0) return false;
data.splice(index, 1);
return true;
};
indexer.size = function () {
return data.length;
};
// return the function in the constructor. This is the main trick
return indexer;
}
var map = new FakeMap();
var key1 = {};
var key2 = {};
// put values
map(key1, 1);
map(key2, 2);
// get values
console.log(map(key1)); // 1
console.log(map(key2)); // 2
// remove by key
map.remove(key1);
console.log(map.size());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment