Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

Some notes on organizing are recorded in the column 👉 [Functional programming] and [JS Basics].


preface

A simple pure function:

// Compare two pure functions of size
function compareSize(a,b) {
  return a > b
}

console.log(compareSize(1.2)); // false
console.log(compareSize(2.2)); // false
console.log(compareSize(3.2)); // true
Copy the code

In the pure function above, we compare the two values, and the parameter B has the same value 2 in all three calls to the function.

In that case, let’s rewrite it.

function compareSize(a) {
  let b =2
  return a > b
}

console.log(compareSize(1)); // false
console.log(compareSize(2)); // false
console.log(compareSize(3)); // true
Copy the code

After rewriting the code, the argument becomes an A, although the result is the same as last time, the function compareSize is also a pure function.

But there is a fixed parameter b inside, which actually becomes hardcode 🤯. Is a kind of solidified code, code in the internal write dead, will be very troublesome to modify.

Let’s try it another way:

function compareSize(b) {
  return function (a) {
    return a > b
  }
}

const hasThanTarget = compareSize(2)
console.log(hasThanTarget(1)); // false
console.log(hasThanTarget(2)); // false
console.log(hasThanTarget(3)); // true
Copy the code

And the last one is actually a way of currizing a function, which is to convert a function with many parameters into a function with one parameter.

Definition of the Currization of a function

In computer science, Currying, also translated as carryization or callization, is a technique of converting a function that takes multiple arguments into a function that takes a single argument (the first argument of the original function), and returning a new function that takes the remaining arguments and returns a result.

The technique was named by Christopher Strackey after logician Haskell Gary, although it was invented by Moses Schonfinkel and Gottlob Frege 😂.


The currization of a function

Parameters of reuse

Through the Method of Currization, the parameters are cached to the internal parameters of the closure, and then the cached parameters are combined with the parameters passed into the function to execute, so as to realize the reuse of parameters, reduce the generality and improve the applicability.

🌰 example: a method of checking regular files that can be curried.

function curryingCheck(reg) {
  return function (txt) {
    return reg.test(txt);
  };
}

// ES6
let curryingCheck = reg= > (txt= > reg.test(txt))
Copy the code

Use:

// Re: Only numbers can be entered
let hasNumber = curryingCheck(/^\d+$/);
console.log(hasNumber("test")); // false
console.log(hasNumber(1)); // true

// Re: check the mobile phone number
let hasPhone = curryingCheck(/ ^ (0 | 86 | 17951)? (13 15 [012356789] [0-9] | | 166 | 17 [3678] 18 [0-9] | | 14 [57]) [0-9] {8} $/);
console.log(hasPhone("test")); // false
console.log(hasPhone(18577331234)); // true
Copy the code

Delay to run

If a call to a Currified function passes in arguments that are not called, the arguments are added to the array and stored until no arguments are passed in.

🌰 example: summing operations that can carry out Currying.

function add() {
    var args = Array.prototype.slice.call(arguments);
    var _that = this;
    return function() {
        var newArgs = Array.prototype.slice.call(arguments);
        var total = args.concat(newArgs);
        if(!arguments.length) {
            var result = 1;
            for(var i = 0; i < total.length; i++) {
                result *= total[i];
            }
            return result;
        }
        else {
            returnadd.apply(_that, total); }}}Copy the code

Use:

add(1) (2) (3) ();/ / 6
add(1.2.3) ();/ / 6
Copy the code

The principle and simulation of function Kerrization

The principle of

Using the closure principle, you can create a non-destructible scope during execution, then store the pre-processed content in this non-destructible scope, and return a function with the least arguments.

Analog implementation

The above example is not general-purpose enough, so let’s simulate implementing a (source)

function curry(fn, args) {
  var length = fn.length;

  args = args || [];

  return function () {
    var _args = args.slice(0), arg, i;

    for (i = 0; i < arguments.length; i++) {
      arg = arguments[i];
      _args.push(arg);
    }
    if (_args.length < length) {
      return curry.call(this, fn, _args);
    } else {
      return fn.apply(this, _args); }}; }Copy the code

Use:

var fn = curry(function (a, b, c) {
  console.log([a, b, c]);
});

fn("a"."b"."c"); // ["a", "b", "c"]
fn("a"."b") ("c"); // ["a", "b", "c"]
fn("a") ("b") ("c"); // ["a", "b", "c"]
fn("a") ("b"."c"); // ["a", "b", "c"]
Copy the code

The Coriolization function is used in Lodash

🎯 recommended for use at work

_.curry(func)

  • Function: creates a function that takes one or more arguments of func, executes func and returns the result of execution if all the arguments needed by func are provided, otherwise returns the function and waits for the rest of the arguments to be accepted.
  • Parameters: functions that require currization
  • Return value: The currified function

Use:

var abc = function(a, b, c) {
  return [a, b, c];
};

var curried = _.curry(abc);

curried(1) (2) (3);
// => [1, 2, 3]

curried(1.2) (3);
// => [1, 2, 3]

curried(1.2.3);
// => [1, 2, 3]
Copy the code

Corrified summary

Currization is an extremely useful technique for functional JavaScript.

It allows you to produce a concise, easy to configure, uniform library that is fast and readable to use.

Adding currization to your coding practices will encourage you to apply it to some functions in your entire code, which avoids a lot of potential rework and can help you develop good habits about naming functions and handling function arguments.


reference

  • What is the Currization of a function
  • Functional programming introductory tutorial
  • Currie – WIKI
  • Haskell Gary – Baidu Encyclopedia
  • Currization of JavaScript topics
  • 2019 Front-end interview series – JS high frequency handwritten code questions
  • The function is currified
  • Corrification in JS
  • Master the Currization of JavaScript functions
  • Js basic chapter – JavaScript Currie function details