Last active
May 3, 2017 20:56
-
-
Save nicnocquee/67d44687984b4c1a3f15456ffa89ba93 to your computer and use it in GitHub Desktop.
JS function to resolve key path for Immutable.js
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
// @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