Created
March 23, 2025 14:27
-
-
Save attitude/025817ff9d92a219491db0c03a40c88a to your computer and use it in GitHub Desktop.
Functional utility to recover from `undefined` values
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
function recover<T, F, A extends any[]>( | |
fn: (...args: A) => T | undefined, | |
fallback: () => F | |
): (...args: A) => T | F; | |
function recover<T, F>(value: T | undefined, fallback: () => F): T | F; | |
function recover<T, F, A extends any[]>( | |
valueOrFn: T | undefined | ((...args: A) => T | undefined), | |
fallback: () => F | |
): T | F | ((...args: A) => T | F) { | |
if (typeof valueOrFn === "function") { | |
return (...args: A) => { | |
const result = (valueOrFn as (...args: A) => T | undefined)(...args); | |
return result === undefined ? fallback() : result; | |
}; | |
} else { | |
return valueOrFn === undefined ? fallback() : valueOrFn; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment