Currie,

meaning

  • The technique of first filling a function with several arguments (and then returning a new function) is called Currying.
  • When a function has more than one argument, it is called with a portion of the argument (which will never change) and returns a new function that takes the remaining arguments and returns the result

Code

A simple example of currization

//es5
function checkAge (min) {
    return function (age) {
        return age >= min
    }
}

// es6
const checkAge = min= > ((age) = > age >= min)

/ / curry
checkAge16 = checkAge(12)
checkAge18 = checkAge(18)

/ / execution
checkAge16(16)
// true
checkAge18(22)
// true
Copy the code

The most commonly used Curryization function bind()

// Handwriting implementation
Function.prototype.myBind = function() {
    var self = this
    var args = Array.prototype.slice.call(arguments) // Convert arguments to arrays
    var context = args[0] // Save the this context that needs to be bound

    // Return a new function
    return function() {
        return self.apply(context, Array.prototype.concat.call(args, Array.prototype.slice.call(arguments)))}}// Test case
function func(age, sex) {
    const str = `The ${this.name}Is a${age}At the age of${sex}Classmate `
    console.log(str)
}
const student = {
    name: 'Ming'
}
const newFunc = func.myBind(student, 18)
newFunc('male')
Copy the code

Implement a Curryization function

function getSum (a, b, c) {
    return a + b + c
}

// console.log(getSum.length)

const curried = curry(getSum)
console.log('curried(1, 2, 3)', curried(1.2.3))
console.log('curried(1)(2, 3)', curried(1) (2.3))
console.log('curried(1)(2)(3)', curried(1) (2) (3))

function curry (func) {
    return function curriedFn (. args) {
        // Check whether the number of arguments and parameters is the same
        if (args.length < func.length) {
            // If not, a new function is returned, receiving subsequent arguments
            return function () {
                returncurriedFn(... args.concat(Array.from(arguments)))}}else if (args.length === func.length) {
            // call func
            returnfunc(... args) } } }Copy the code
/ / the interview questions
// plus(1)(1)(2)(3)(5).toString() === 12

function plus (n) {
    let sum = n
    let add = function (n) {
        sum += n
        return add
    }

    add.toString = function () {
        return sum
    }

    return add
}


const res = plus(1) (1) (2) (3) (5).toString()
console.log(res === 12)
Copy the code

conclusion

  • Currization allows us to pass fewer arguments to a function, resulting in a new function that has memorized some of the fixed arguments
  • This is a cache of function parameters
  • Make functions more flexible and smaller in granularity
  • You can convert a multivariate function into a unary function, and you can combine functions to produce powerful functions

Good study will not be bad, I am your little airline, we progress together