Last active
October 21, 2015 06:40
-
-
Save voltrevo/ff94ae14bfe749a31740 to your computer and use it in GitHub Desktop.
A generalized map in ES5 based on linear lookup on strict comparison
This file contains hidden or 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
'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