R

E

A

C

T

O

xamples 

epeat

ode

pproach

ptimize

est

REACTO: Steph Curry

 

Currying

  • What is currying?
    • ​​Cookin up the sauce, chef curry with them pots boy

Currying

a, b

curry

a

b

a b

Formal Definition:

"Currying is the process by which a function of N arguments is implemented as N single-argument functions such that first of them takes in the first argument and returns a function which takes in the 2nd argument and so on, until the Nth single-argument function finally returns the value of the multi-argument function being implemented."

Exampre

function addAllFour(var1, var2, var3, var4) {
	return var1 + var2 - var3 * var4;
}

var curriedDoSomething = curry(doSomething) // closure memory -> []

var firstReturn = curriedDoSomething(1) // closure memory -> [1]

var secondReturn = curriedDoSomething(2) // closure memory -> [1 , 2]

var thirdReturn = curriedDoSomething(3) // closure memory -> [1, 2, 3]

var fourthReturn = curriedDoSomething(4) // -9 (1 + 2 - 3 *4)

Exampre 2

function doMath(a, b, c, d) {
    return a + b - c * d;
}

var curried = curry(doMath);

var makeOne = curried(1);
var makeTwo = makeOne(2);

var returned1 = makeOne(3, 4, 5); // -16 (1 + 3 - 4 * 5)
var returned2 = makeTwo(4, 5) // -17 (1 + 2 - 4 * 5)

Now you must be Steph Curry

  • Implement the "curry" function to accomplish the previous example
  • Things to keep in mind
    • You have to know how many arguments the function that you are currying  takes in
      • The previous example had 4 parameters
    • The function you return from currying must have some sorts of ways to accumulate the number of following arguments
    • Once your accumulation meets the number of parameters the original function takes in, the curried function that brought in the nth-argument will return whatever the original function returns

Possible solution

function curry( originalFunc ) {
	var originalLength = originalFunc.length;

	function resolver() {
		var memory = Array.prototype.slice.call( arguments );
		
		var whatToReturn = function() {
			var next,
				args = Array.prototype.slice.call( arguments ),
				copy = memory.concat(args);

			if (copy.length >= originalLength) {
				next = originalFunc;
			} else {
				next = resolver;
			}

			return next.apply(null, copy);
		};

	
		return whatToReturn;
	}

	return resolver();
}

Bonus

  • The thing about the example and solution previously is that you have no control with orders. The arguments will always be passed left to right
  • Edit the curry function and the example to where you control the order of the arguments
function doMath(a, b, c, d) {
    return a + b - c * d;
}

var steph1 = curried(/* Do Something */ 1);
var steph2 = steph1(1, 2, 3) // 0 (1 + 2 - 3 * 1)

Possible Solution

Reacto: curry

By Sam Chun

Reacto: curry

Technical interview practice problem

  • 1,935