Handwritten Collerization accumulator

create by db on 2021-5-27 18:26:30

Recently revised in 2021-5-27 18:26:34

Idle time to have a tight mind, busy time to have leisure fun

directory

  • preface

  • The body of the

    • First, Currying
    • Two, Kerridian accumulator
  • conclusion

  • Reference documentation

preface

Returns the directory

Ask questions and don’t talk nonsense.

The body of the

First, Currying

Returns the directory

Currying is a technique that converts a function that takes multiple arguments into a function that takes a single argument, and returns a new function that takes the remaining arguments and returns a result.

explain

  • Managed through closures

  • Support for chain calls

  • Returns a function per run

    That is, the technique of returning a new function each time you run by replacing multiple arguments with one

For example,

// The normal add function
function add(x, y) {
  return x + y
}

/ / after Currying
function curryingAdd(x) {
  return function (y) {
    return x + y
  }
}

add(1.2) / / 3
curryingAdd(1) (2) / / 3.
Copy the code

Application scenarios

1. Parameter multiplexing

In a regular check, it would normally be ok to just call the check function, but if I have a lot of places to check for numbers, THEN I need to reuse the first parameter reg, so that I can call hasNumber, hasLetter, and so on. Make parameters reusable and easier to call.

// Normal rege.test (TXT)

// Function encapsulation
function check(reg, txt) {
  return reg.test(txt)
}

// Check the number
check(/\d+/g.'test') // false
// Check letters
check(/[a-z]+/g.'test') // true

/ / after Currying
function curryingCheck(reg) {
  return function (txt) {
    return reg.test(txt)
  }
}
// Check the number
var hasNumber = curryingCheck(/\d+/g)
// Check letters
var hasLetter = curryingCheck(/[a-z]+/g)

hasNumber('test1') // true
hasNumber('testtest') // false
hasLetter('21212') // false
Copy the code

2. Return the function and delay the execution

The mechanism used by javascript, like bind, is called Currying.

Function.prototype.bind = function (context) {
  var _this = this
  var args = Array.prototype.slice.call(arguments.1)
  return function () {
    return _this.apply(context, args)
  }
}
Copy the code

Two, Kerridian accumulator

Classic interview question, The Creelian accumulator

// Implement an add method that meets the following expectations: add(1)(2)(3) = 6; add(1, 2, 3)(4) = 10; add(1)(2)(3)(4)(5) = 15;Copy the code

1. Determine the parameters of the function of the Implementation of coriolization

// Only four arguments can be passed
function add(a, b, c, d) {
  return a + b + c + d
}
// Currization function
function curry(fn) {
  return function curried(. args) {
    if (args.length < fn.length) {
      // Check whether the accepted argument is less than the length of the function argument
      return function () {
        // The parameter is not long enough
        returncurried(... args, ... arguments) } }returnfn(... args)// This is not required to change}}let curryAdd = curry(add)

/ / test
console.log(curryAdd(1) (2) (3) (4)) / / 10
console.log(curryAdd(1.2) (2.4)) / / 9
Copy the code

2. Infinite accumulation of uncertain parameters

// add function
function add(arr) {
  return arr.reduce((acc, item) = > {
    return acc + item
  })
}
// Currization function
function curry(fn) {
  let argList = []
  // Internally declare a function that uses closure properties to hold _args and collect all parameter values
  return function collect(. args) {
    // Check whether there are arguments
    if (args.length) {
      argList = [...argList, ...args]
      return collect
    }
    return fn(argList)
  }
}

let curryAdd = curry(add)

/ / test
console.log(curryAdd(1) (2) (3) ())/ / 6
console.log(curryAdd(1.2.3) (4) ())/ / 10;
console.log(curryAdd(1) (2) (3) (4) (5) ())/ / 15;
console.log(curryAdd(1) (2) (3) (4) (10.20) ())/ / 40

// If () does not pass arguments, the summation function will be called
Copy the code

3. A function realizes infinite accumulation of uncertain parameters

function add() {
  // On the first execution, an array is defined to store all the parameters
  const argList = Array.from(arguments)

  // Internally declare a function that uses closure properties to hold _args and collect all parameter values
  const collect = function () { argList.push(... arguments)return collect
  }

  // Take advantage of the implicit conversion feature to implicitly convert when finally executed and calculate the final value returned
  collect.toString = function () {
    return argList.reduce((a, b) = > a + b, 0)}return collect
}

/ / test
console.log(add(1) (2) (3)) / / 6
console.log(add(1.2.3) (4)) / / 10;
console.log(add(1) (2) (3) (4) (5)) / / 15;

var a = add(1) (2) (3) (4) // f 10
var b = add(1.2.3.4) // f 10
var c = add(1.2) (3.4) // f 10
var d = add(1.2.3) (4) // f 10

// You can use the properties of implicit conversions to participate in calculations
console.log(a + 10) / / 20
console.log(b + 20) / / 30
console.log(c + 30) / / 40
console.log(d + 40) / / 50

// You can also pass in the argument, and the result is evaluated again using an implicit conversion
console.log(a(10) + 100) / / 120
console.log(b(10) + 100) / / 120
console.log(c(10) + 100) / / 120
console.log(d(10) + 100) / / 120
Copy the code

Tips

What should be added is the implicit conversion of functions. When we use a function directly to evaluate something else, by default the function calls toString, converting the function body directly to a string to evaluate.

function fn() {
  return 20
}
console.log(fn + 10) Function fn() {return 20}10
Copy the code

In order to print the results we want, we need to override the toString method ourselves

function fn() {
  return 20
}
fn.toString = function () {
  return 30
}

console.log(fn + 10) / / 40
Copy the code

In addition, when we override the valueOf method of a function, we can also change the result of the implicit conversion of the function.

function fn() {
  return 20
}
fn.valueOf = function () {
  return 60
}

console.log(fn + 10) / / 70
Copy the code

When we override both the toString and valueOf methods of a function, the final result takes the result returned by valueOf.

function fn() {
  return 20
}
fn.valueOf = function () {
  return 50
}
fn.toString = function () {
  return 30
}

console.log(fn + 10) / / 60
Copy the code

conclusion

Returns the directory

The road ahead is long, and I see no end.

reference

  • Javascript function to the add (1) (2) (3) (4) to realize infinite accumulation – analytical | CSDN principle – weixin_33778544 step by step
  • The add () unlimited calls to the edge of the gold ingot | CSDN – smile
  • Add (1)(2)(3)(4)… Infinite accumulation | CSDN farmers – baby not code

Postscript: Hello friends, if you think this article is good, remember to give a thumbs-up or star, your thumbs-up and star is my motivation to write more and richer articles!Making the address

Document agreement



dbThe document library 由 dbusingCreative Commons Attribution – Non-commercial Use – Same way Share 4.0 International LicenseGrant permission.

Based on thegithub.com/danygitgitOn the creation of works.

Use rights other than those authorized by this License agreement may be obtained from
Creativecommons.org/licenses/by…Obtained.