Skip to content

Instantly share code, notes, and snippets.

@voltrevo
Last active October 21, 2015 06:40
Show Gist options
  • Save voltrevo/ff94ae14bfe749a31740 to your computer and use it in GitHub Desktop.
Save voltrevo/ff94ae14bfe749a31740 to your computer and use it in GitHub Desktop.
A generalized map in ES5 based on linear lookup on strict comparison
'use strict';
var assert = require('assert');
module.exports = function(createDefaultValue) {
var map = {};
var keyValuePairs = [];
var lookup = function(key) {
var matches = keyValuePairs.filter(function(kv) {
return kv.key === key;
});
assert(matches.length <= 1);
return matches;
};
map.get = function(key) {
var matches = lookup(key);
if (matches.length === 0) {
var kv = {
key: key,
value: createDefaultValue();
};
keyValuePairs.push(kv);
return kv.value;
};
return matches[0].value;
};
map.set = function(key, value) {
var matches = lookup(key);
if (matches.length === 0) {
keyValuePairs.push({
key: key,
value: value
});
} else {
matches[0].value = value;
}
};
return map;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment