ctrlplusb / react-universally

A starter kit for universal react applications.
MIT License
1.7k stars 244 forks source link

Lazy resolution in ternaries #463

Closed michaeljonathanblack closed 7 years ago

michaeljonathanblack commented 7 years ago

What is the purpose of the ifElse alternative to a simple ternary?

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'
 */
export default function ifElse(condition) {
  return (then, or) => (execIfFunc(condition) ? execIfFunc(then) : execIfFunc(or));
}

Aren't ternaries already resolved lazily in JavaScript?

ctrlplusb commented 7 years ago

Yeah, you are correct, however a ternary isn't as composable as used within the webpack config generation. TBH I have started moving away from this implementation in some of my more recent work, into a much simpler form.

michaeljonathanblack commented 7 years ago

Great! Makes sense, just wanted to make sure I understood the things.

Thanks for the clarification! 💃