Last active
November 1, 2019 21:28
-
-
Save kevinkace/00efbefe0c601a874ea1809389428232 to your computer and use it in GitHub Desktop.
like [].find(), but return a value of your choosing
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
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