Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kraftdorian/61022b5a2568b87d1873899c548cfd08 to your computer and use it in GitHub Desktop.
Save kraftdorian/61022b5a2568b87d1873899c548cfd08 to your computer and use it in GitHub Desktop.
Assoc list value search by key, inspired with Haskell language style
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);
}
};
@kraftdorian
Copy link
Author

kraftdorian commented Jun 26, 2021

Usage:

const input = [
  ["a", 1],
  ["b", 2],
  ["c", [
    ["d", 4],
    ["e", [
      ["f", 6],
      ["g", 7]
    ]]
  ]]
];

const output = findAssocListValueByKey(input, "f");
console.log(output); // gives: Symbol(Just 6)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment