This is the 31st day of my participation in the genwen Challenge

Although it is not a challenge, but still want to write, next is their own challenge

This series also does not have any tricks, is to complete the usual interview some handwriting functions, test these simple implementation of the advantage is that you can see the basic coding level, and take a short time, a more comprehensive view of your code strength. Generally, there are not many boundary conditions, so that the interview time is not enough, the investigation is not comprehensive.

If you don’t know or are not clear about the API, just ask the interviewer directly, how to use the API under Google anyone can immediately understand the knowledge also can’t see the level. The key is in the implementation process, and your coding status, habits, clarity of thought and so on.

Note that it is a simple implementation, not a complete implementation, it is important to clear the concept and clear implementation ideas, it is suggested to explain the concept first => write use cases => write pseudo-code => then realize specific functions, and then optimize, step by step.

Yesterday we looked at the handwritten implementation of the array map(), filter() and today we’ll try reduce()

23. Array.prototype.reduce()

What is the

The reduce() method performs a reducer function (in ascending order) that you provide on each element in the array, summarizing its results into a single return value.

example

const array1 = [1.2.3.4];
const reducer = (accumulator, currentValue) = > accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15
// 5 as a parameter is the initial value
Copy the code

The reducer function receives four parameters:

  • Accumulator (ACC)
  • Current Value (CUR)
  • Current Index (IDX)
  • Source Array (SRC)

The return value from your Reducer function is assigned to the accumulator and is remembered in each iteration of the array and eventually becomes the final single result value.

grammar

arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
Copy the code

parameter

  • callback
    • The function that executes each value in the array (except the first value if no initialValue is provided), with four arguments:
      • accumulator: the cumulativeThe return value of the cumulative callback; It is the cumulative value, or initialValue, returned when the callback was last invoked (see below).
      • currentValueThe element in the array being processed.
      • indexOptional: Index of the current element being processed in the array. If providedinitialValue, the start index number is0Otherwise from the index1The start.
      • arrayOptional: An array of calls to reduce()
  • initialValueoptional
    • As aFirst call callbackWhen the functionThe value of the first argument(Initial value). If no initial value is provided, the first element in the array is used.
    • Calling reduce on an empty array with no initial value will report an error.

Returns the result of the cumulative processing of the value function.

For more information about reduce usage, refer to MDN

Reduce; reduce; reduce 2. shorten; Reduce, you can think of it as an array that reduces to a single value.

In other words, iterate through the array and return a summary.

Handwritten implementation

Let’s summarize the main points before we implement:

Reduce executes a callback function for each element in the array (excluding deleted or never assigned elements in the array), taking four arguments:

  • An accumulator cumulative device
  • The current value currentValue
  • CurrentIndex indicates the currentIndex
  • Array an array

Accumulator and currentValue are two different values when the callback function is first executed:

  1. If initialValue is provided:
  • accumulatorValues forinitialValue
  • currentValueTake theThe first value
  1. If not providedinitialValue, then:
  • accumulatorTake theThe first value
  • currentValueTake theThe second value.
  • Calling reduce on an empty array with no initial value will report an error.

Before looking at the implementation code, it is recommended to look at the map implementation from the previous article. Many of the ideas are the same

Array.prototype.myReduce = function(callback, initialValue) {

  if (this= =null) {
    throw new TypeError("Cannot read property 'reduce' of null or undefined");
  }
  if (typeofcallback ! = ='function') {
    throw new TypeError(callback + ' is not a function')}let O = Object(this)

  // The final result is an accumulator
  let accumulator

  let k = 0
  
  // Determine the initial value condition
  if (initialValue) {
    // provide the initialValue. Accumulator is initialValue
    accumulator = initialValue
  } else {

    Calling reduce on an empty array with no initial value will result in an error.
    if (O.length === 0) {
      throw new TypeError('Reduce of empty array with no initial value');
    }

    The in operator returns true if the specified property is in the specified object or its stereotype chain
    // Loop judgment starts when there is an attribute K on O and its prototype chain
    while(k < O.length && ! (kin O)) {
      k++;
    }

    // No initial value is provided. 'Accumulator' takes the first value ** in the array
    accumulator = O[k++]
  }

  while (k < O.length) {
    if (k in O) {
      let currentValue = O[k]
      accumulator = callback(accumulator, currentValue, k, O)
    }
    k++
  }

  return accumulator
}

const array1 = [1.2.3.4];
const reducer = (accumulator, currentValue) = > accumulator + currentValue;

const array2 = [{label: 'ten'.num: 10}, {label: 'eight'.num: 8}];
const reducer2 = (acc, cur) = > {
  return {
    label: `${acc.label} ${cur.label}`.num: acc.num + cur.num
  }
}

// 1 + 2 + 3 + 4
console.log(array1.myReduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.myReduce(reducer, 5));
// expected output: 15

console.log(array2.myReduce(reducer2, {label: '一'.num: 0}));
Copy the code

In addition, we recommend another series of articles, very simple, on the front of the advanced students are very effective, wall crack recommended!! Core concepts and algorithms disassembly series remember to like ha

If you want to brush the questions with me, you can add me on wechat. Click here to make a friend Or search my wechat account, infinity_9368. You can chat with me and add my secret code “Tianwang Gaidihu”. Verify the message please send me Presious tower shock the rever Monster, I see it through, after adding I will do my best to help you, but pay attention to the way of asking questions, it is suggested to read this article: the wisdom of asking questions

reference

  • Developer.mozilla.org/zh-CN/docs/…