Last active
June 21, 2017 15:35
-
-
Save sebringj/348efe07f858d71d9418c8e0d8d6be18 to your computer and use it in GitHub Desktop.
JavaScript LookupList
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
/* | |
use like so: | |
const lookupList = new LookupList({ a: 1 }, { b: 2 }, { c: 3 }) | |
console.log(lookupList.valueByKey('a')) // 1 | |
console.log(lookupList.keyByValue(1)) // "a" | |
console.log(lookupList.keysByValue(1)) // ["a"] | |
console.log(lookupList.valueByIndex(0)) // 1 | |
console.log(lookupList.keyByIndex(0)) // "a" | |
console.log(lookupList.indexByKey('a')) // 0 | |
*/ | |
class LookupList { | |
constructor() { | |
this._hashKey = {} | |
this._hashVal = {} | |
this._list = [] | |
this.length = 0; | |
const objList = [].slice.call(arguments) | |
for (let listObj of objList) | |
this._push(listObj) | |
} | |
_push(listObj) { | |
if (typeof listObj !== 'object') | |
throw 'invalid argument in constructor' | |
let keys = Object.keys(listObj) | |
if (keys.length !== 1) | |
throw 'invalid argument in constructor' | |
let key = keys[0] | |
let val = listObj[key]; | |
let obj = { key, val, index: this._list.length } | |
if (this._hashKey[key]) | |
throw `duplicate key found: ${key}` | |
this._hashKey[key] = obj | |
if (this._hashVal[val]) | |
this._hashVal[val].keys.push(key) | |
else | |
this._hashVal[val] = { keys: [key] } | |
this._list.push(obj) | |
this.length = this._list.length | |
} | |
valueByKey(key) { | |
if (!this._hashKey[key]) return undefined | |
return this._hashKey[key].val | |
} | |
keyByValue(val) { | |
if (!this._hashVal[val]) return undefined | |
return this._hashVal[val].keys[0] | |
} | |
keysByValue(val) { | |
if (!this._hashVal[val]) return undefined | |
return this._hashVal[val].keys | |
} | |
valueByIndex(index) { | |
if (!this._list[index]) return undefined | |
return this._list[index].val | |
} | |
keyByIndex(index) { | |
if (!this._list[index]) return undefined | |
return this._list[index].key | |
} | |
indexByKey(key) { | |
if (!this._hashKey[key]) return -1 | |
return this._hashKey[key].index | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment