Created
December 12, 2011 23:29
-
-
Save nodirt/1469647 to your computer and use it in GitHub Desktop.
Indexers in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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