Skip to content

Instantly share code, notes, and snippets.

@nicnocquee
Last active May 3, 2017 20:56
Show Gist options
  • Save nicnocquee/67d44687984b4c1a3f15456ffa89ba93 to your computer and use it in GitHub Desktop.
Save nicnocquee/67d44687984b4c1a3f15456ffa89ba93 to your computer and use it in GitHub Desktop.
JS function to resolve key path for Immutable.js
// @flow
import Immutable from 'immutable'
export const resolveKeyPaths = (source: Immutable.Collection, keypaths: Array<any>) => {
const isFunction = (obj: any) => {
return !!(obj && obj.constructor && obj.call && obj.apply);
};
var resolvedKeyPaths = []
keypaths.forEach((value, index) => {
if (isFunction(value)) {
var subSource = source
if (resolvedKeyPaths.length > 0) {
subSource = source.getIn(resolvedKeyPaths)
}
const indexToAdd = subSource.findIndex(value)
if (indexToAdd > -1) resolvedKeyPaths.push(indexToAdd)
else {
console.error(`Cannot find index using ${value.toString()}`)
throw `Error in ${index}th keypath`
}
} else {
resolvedKeyPaths.push(value)
}
})
return resolvedKeyPaths
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment