Created
June 26, 2021 15:39
-
-
Save kraftdorian/61022b5a2568b87d1873899c548cfd08 to your computer and use it in GitHub Desktop.
Assoc list value search by key, inspired with Haskell language style
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
const Nothing = Symbol('Nothing'); | |
const Just = (value) => Symbol("Just " + JSON.stringify(value)); | |
const isAssocList = (value) => { | |
return Array.isArray(value) && value.length === 2; | |
}; | |
const findAssocListValueByKey = (list, key) => { | |
const [assocItem, ...items] = list; | |
if (undefined === assocItem) { | |
return Nothing; | |
} | |
const [assocKey, assocVal] = assocItem; | |
if (assocKey === key && !isAssocList(assocVal)) { | |
return Just(assocVal); | |
} else if (isAssocList(assocVal)) { | |
return findAssocListValueByKey([...assocVal, ...items], key); | |
} else { | |
return findAssocListValueByKey(items, key); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: