Created
October 11, 2019 17:34
-
-
Save benbayard/cf0ebc7670e0c54495973de553411cc8 to your computer and use it in GitHub Desktop.
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
/** | |
* 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