This is the 9th day of my participation in Gwen Challenge

First of all, the reason why it’s called Currization is because it was named by Christopher Strachey after the logician Haskell Curry. So regardless of the name, we can also remember harmonic granulation (passing parameters one by one).

This is a function that transforms a method that takes multiple arguments into a function that takes a single argument, and returns a new function that takes the rest.

function

Let’s start with a simple function

function multiply(x, y){
    return x * y;
}

multiply(2.5); / / 10
Copy the code

All this function does is multiply the two functions. Next, let’s make this function a function that takes only one argument and can hold the values passed in earlier.

function curry_multiply(x, y) {
    return (y) = > {
        returnx * y; }}let multiply2 = curry_multiply(2);
multiply2(5); / / 10

let multiply5 = curry_multiply(5);
multiply5(2); / / 10
Copy the code

For those of you familiar with closures, the above function returns a new function and holds the value of the x variable. This allows the value of curry_multiply passed in to be retained, making it easier to call in different cases.

Here is a general Currified function, which is just a simplified version of a function that needs to be judged in practice.

function curry(fn, ... args) {
		return (. arg) = > {
			returnfn(... args, ... arg); }}function volumn(x, y, z) {
	return x*y*z;
}

let test2 = curry(volumn, 2);
let test10 = curry(test2, 5);
test10(10); / / 100
Copy the code

The main purpose of the Curry function is to call the first argument passed in as a function, pass in the second argument as an argument to fn, and pass in the remaining arguments. This allows us to simply reuse different arguments of the same function.

Application scenarios

What is used more is that most similar functions can be reused. In the case of multiple parameters, some inherent parameters can be encapsulated multiple times.

function checkPhone(phoneNumber) {
    return /^1[34578]\d{9}$/.test(phoneNumber);
}
function checkEmail(email) {
    return /^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/.test(email);
}
Copy the code

This should be common in projects and can be improved a bit with Curry.

let _check = createCurry(check);

let checkPhone = _check(/^1[34578]\d{9}$/);
let checkEmail = _check(/^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/);
Copy the code