Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

currying function instead of if condition in javascript

Tried to use curry function to write if condition (without "if" "true" and "false"). Have no idea how to do it right! Can anyone help and show me how to do it?

const True = () => {};
const False = () => {};
const If = True => False => ifFunction(True)(False);

const ifFunction = If(True);
ifFunction('1')('2'); // 1

console.log(If(True)('1')('2'));  // 1
console.log(If(False)('1')('2')); // 2

It should return 1 or 2 depends on which function is getting pass to if condition. But this code does not work at all.

like image 470
Lex27 Avatar asked Jan 06 '20 10:01

Lex27


People also ask

What is the main reason for currying a function in Javascript?

Currying is a checking method to make sure that you get everything you need before you proceed. It helps you to avoid passing the same variable again and again. It divides your function into multiple smaller functions that can handle one responsibility.

Does javascript support currying?

Currying is a process in functional programming in which we can transform a function with multiple arguments into a sequence of nesting functions. It returns a new function that expects the next argument inline.

What is the benefit of currying JS?

The main benefit of currying is when you need to use the same call with some of the same parameters a lot i.e it helps to avoid passing the same variable again and again. In these situations, currying becomes a good technique to use. Currying will make your code easier to refactor.

Is currying same as closure?

Currying means that the closure does not have to receive all of its arguments at once, but separately. I've found this useful metaphor around the internet: Think of currying as adding ingredients (arguments, or other spices) to a function one by one. You can drop some arguments now, and other arguments as you go.


Video Answer


1 Answers

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
like image 123
Nina Scholz Avatar answered Sep 21 '22 23:09

Nina Scholz