Skip to content

Instantly share code, notes, and snippets.

@kevinkace
Last active November 1, 2019 21:28
Show Gist options
  • Save kevinkace/00efbefe0c601a874ea1809389428232 to your computer and use it in GitHub Desktop.
Save kevinkace/00efbefe0c601a874ea1809389428232 to your computer and use it in GitHub Desktop.
like [].find(), but return a value of your choosing
function findValue(collection, predicate) {
let value;
collection.some(c => {
const p = predicate(c)
if (p) {
value = p;
return true;
}
return false;
});
return value;
}
const users = [
{ name : "Kevin", id : 123 },
{ name : "someoneElse", id : 456 }
];
function getIdFromName(_name) {
return findValue(users, ({ name, id }) => name === _name ? id : false);
}
getIdFromName("Kevin");
// 123
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment