Skip to content

Instantly share code, notes, and snippets.

@blackbing
Last active December 10, 2016 14:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blackbing/bf53c851ef8ddcf7383023fac8552902 to your computer and use it in GitHub Desktop.
Save blackbing/bf53c851ef8ddcf7383023fac8552902 to your computer and use it in GitHub Desktop.
findObjectFromArray quickly
// @param list: array
// @param matcher: function to check match
// @param reverse: find from last if true
// Example:
// const matchedMessage = findObjectFromArray(state.list, (val) => {
// return (val.rootId === key);
// }, true);
// const matchedIndex = matchedMessage[0];
// const matchedObject = matchedMessage[1];
export default function (list, matcher, reverse = false) {
let matchedIndex;
let matchedObject;
let target = list;
if (reverse) {
// prevent reverse oringinal array
target = list.slice().reverse();
}
const matched = target.some((val, index) => {
if (matcher(val)) {
matchedIndex = index;
matchedObject = val;
return true;
}
return false;
});
if (matched) {
if (reverse) {
matchedIndex = (target.length - 1) - matchedIndex;
}
return [matchedIndex, matchedObject];
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment