Created
August 14, 2018 07:20
-
-
Save jonniek/adf69d999ac94596ba523166082b094b to your computer and use it in GitHub Desktop.
Two way key value hashmap/object/store in JavaScript. Get keys with values or values with keys.
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
/** | |
* Two way key value store. | |
* When you want to get key with value or value with a key. | |
* | |
* examples: | |
* var store = twoWayKeyValueStore([ [200, "ok"], [401, "unauthorized"] ]) | |
* store.get(401) // "unauthorized" | |
* store.get("unauthorized") // 401 | |
* store.set(200, "ok").get("ok") // 200 | |
* store.remove("ok").get(200) // undefined | |
* obj = store.values() // { "200": "ok", ... | |
*/ | |
export default function twoWayKeyValueStore(values) { | |
var data = values ? values.reduce((obj, tuple) => { | |
if (obj[tuple[1]] !== undefined) { throw new Error("duplicate key/value " + tuple[1]); } | |
if (obj[tuple[0]] !== undefined) { throw new Error("duplicate key/value " + tuple[0]); } | |
obj[tuple[1]] = tuple[0]; | |
obj[tuple[0]] = tuple[1]; | |
return obj; | |
}, {}) : {}; | |
return { | |
set: function(key, value) { | |
if (data[key] !== undefined) { throw new Error("duplicate key/value " + key); } | |
if (data[value] !== undefined) { throw new Error("duplicate key/value " + value); } | |
data[key] = value; | |
data[value] = key; | |
return this; | |
}, | |
get: function(key) { | |
return data[key]; | |
}, | |
remove: function(key) { | |
var value = data[key]; | |
data[value] = undefined; | |
data[key] = undefined; | |
return this; | |
}, | |
values: function() { return data; } | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment