Created
February 1, 2025 16:04
-
-
Save neatshell/e22f687970ec81cda91fe13ab68969e4 to your computer and use it in GitHub Desktop.
ifElse() HOF
This file contains 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
const execIfFunc = x => (typeof x === 'function' ? x() : x); | |
/** | |
* This is a higher order function that accepts a boolean condition and will | |
* return a function allowing you to provide if/else values that should be | |
* resolved based on the boolean condition. | |
* | |
* @param {Boolean|() => Boolean} condition: | |
* The condition to test against. This can be a function for lazy resolution. | |
* | |
* @return {(X|() => X, Y|() => Y) => X|Y} | |
* A function where the first paramater is the "if" and the second paramater | |
* is the "else". Each of these allows lazy resolving by providing a function. | |
* | |
* @example | |
* const ifDev = ifElse(process.env.NODE_ENV === 'development'); | |
* ifDev('foo', () => 'lazy resolved'); // => 'foo' | |
*/ | |
module.exports = function ifElse(condition) { | |
return (then, or) => (execIfFunc(condition) ? execIfFunc(then) : execIfFunc(or)); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment