Created
July 29, 2017 15:37
-
-
Save mattmccray/f4a5fdb58f0c5ff3a94b6a9b252503f6 to your computer and use it in GitHub Desktop.
Path walker
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
| export function walkPath<T = any>(path: string[] | string): (source: any) => T | undefined { | |
| const steps = Array.isArray(path) ? path : path.split('.') | |
| return (source: any) => steps | |
| .reduce((node, name) => (node && name in node ? node[name] : undefined), source) | |
| } | |
| export function runPath<T = any>(path: string[] | string): (source: any) => T { | |
| const steps = Array.isArray(path) ? path : path.split('.') | |
| return (source: any) => { | |
| const value = steps.reduce((node, name) => | |
| (node && name in node ? node[name] : undefined), source) | |
| return failLoudly(value) | |
| } | |
| } | |
| function failLoudly<T = any>(value: T | undefined): T { | |
| if (typeof value !== 'undefined') | |
| return value | |
| else | |
| throw new Error("Undefined value") | |
| } | |
| // Example: | |
| const getTitle = walkPath<string>('user.posts.0.title') | |
| const getSlug = runPath<string>('user.posts.0.slug') | |
| const title = getTitle({}) | |
| const slug = getSlug({}) | |
| slug.toLowerCase() // Allowed, because it won't return undefined | |
| if (title) { // Title could be undefined, so guard it | |
| title.toUpperCase() | |
| } | |
| else { | |
| console.error("No title!") | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment