Skip to content

Instantly share code, notes, and snippets.

@benbayard
Created October 11, 2019 17:34
Show Gist options
  • Save benbayard/cf0ebc7670e0c54495973de553411cc8 to your computer and use it in GitHub Desktop.
Save benbayard/cf0ebc7670e0c54495973de553411cc8 to your computer and use it in GitHub Desktop.
/**
* Lazily evaluate a deeply nested value
* @param {() => T} getterFn A function that when called either throws an error or returns a value
* @param {T} [defaultValue] A value to return if getterFn does not return a value or the value it returns is undefined
* @returns {T}
* @template T
*/
export function get(getterFn, defaultValue) {
try {
const value = getterFn()
return value === undefined ? defaultValue : value
} catch (error) {
if (error instanceof TypeError) {
return defaultValue
}
throw error
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment