currying function instead of if condition in javascript
By using Church_Booleans, you could use the following functions.
const
TRUE = a => b => a,
FALSE = a => b => b,
IF = p => a => b => p(a)(b);
console.log(IF(TRUE)('1')('2')); // 1
console.log(IF(FALSE)('1')('2')); // 2
Here's a way to implement True
, False
, and If
without using any control flow statements like if...else
or switch..case
, control flow expressions like ?:
, or higher-order functions.
const True = 1;
const False = 0;
const If = Bool => Then => Else => [Else, Then][Bool];
console.log(If(True)('1')('2')); // 1
console.log(If(False)('1')('2')); // 2
This is a defunctionalization of the Church encoding solution. Hence, it's more efficient.