Last active
December 10, 2016 14:35
-
-
Save blackbing/bf53c851ef8ddcf7383023fac8552902 to your computer and use it in GitHub Desktop.
findObjectFromArray quickly
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
// @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