Skip to content

Instantly share code, notes, and snippets.

@mattmccray
Created July 29, 2017 15:37
Show Gist options
  • Select an option

  • Save mattmccray/f4a5fdb58f0c5ff3a94b6a9b252503f6 to your computer and use it in GitHub Desktop.

Select an option

Save mattmccray/f4a5fdb58f0c5ff3a94b6a9b252503f6 to your computer and use it in GitHub Desktop.
Path walker
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