Javascript exercises, handwritten Lodash built-in functions (2)

Table of contents

I. Introduction

1. What is lodash

2. The benefits of handwriting Lodash built-in functions 

2. Today's practice

1. Handwritten differenceWith function: differenceWith(array, values, comparator)

1.1: function function

1.2: Parameter description

1.3: return value

1.4: Implementation code

1.5: Implementation principle

1.6: Test Cases

2. Handwritten drop function: drop(array,n=1)

1.1: function function

2.2: Parameter description

2.3: return value

2.4: Implementation code

2.5: Implementation principle

2.6: Test Cases

3. Handwritten dropRight function: dropRight(array,n=1)

3.1: Function function

3.2: Parameter description

3.3: return value

3.4: Implementation code

3.5: Implementation principle

3.6: Test Cases

4. Handwritten dropRightWhile function: dropRightWhile(array,[predicate=._identity])

4.1: Function function

4.2: Parameter description

4.3: return value

4.4: Implementation code

4.5: Implementation principle

4.6: Test Cases

5. Handwritten fill function: fill(array, value, start=0, end=array.length)

5.1: Function function

5.2: Parameter description

5.3: Return value

5.4: Implementation code

5.5: Implementation Principle

5.6: Test Cases


I. Introduction

1. What is lodash

I believe that friends who are learning the front end should have a better understanding of Lodash . Lodash is a practical JavaScript tool library that provides many commonly used tool functions to simplify JavaScript programming. Lodash provides many utility functions that operate on arrays, numbers, strings, and objects, which makes JavaScript development more efficient, easy, readable, and maintainable.

Benefits of Lodash:

  • Save programming time: By providing packaged and optimized tool methods, the time spent writing various common codes is reduced.
  • Safer: Through the high-abstract API provided by Lodash , the possibility of human error caused by using the built-in JavaScript API is reduced.
  • Faster performance: Lodash has been rigorously tested and optimized for different environments, and its performance is higher than that of its own implementation.

2. The benefits of handwriting Lodash built-in functions 

For beginners , they are often troubled by the fact that they have no place to practice after learning the syntax of Javascript and es6 . After laying a good foundation, many problems will be caused. It is difficult to solve problems independently, and some underlying principle codes are required to be handwritten during interviews. After you write Lodash’s built-in functions by hand, your basic skills will become solid. Follow-up Learning will also become suddenly enlightened.

2. Today's practice

1. Handwritten differenceWith function: differenceWith(array, values, comparator)

1.1: function function

This method is similar to difference  , except that it accepts a  comparator (note: comparator), which is invoked to compare array, valuesthe elements in. The resulting value is selected from the first array. There are two comparator call parameters: (arrVal, othVal) .

1.2: Parameter description

array (Array) : Array to check.

[values] (...Array) : Excluded values.

[comparator] (Function) : The comparator to invoke for each element.

1.3: return value

(Array) : Returns a new array with filtered values.

1.4: Implementation code

function differenceWith(arr1, arr2, comparator) {
  return arr1.filter((item1) => {
    // 检查第二个数组中是否存在与 item1 匹配的项
    // 如果不存在,则返回 true 保留 item1
    // 否则,返回 false,item1 将被忽略
    return !arr2.some((item2) => comparator(item1, item2))
  })
}

1.5: Implementation principle

The specific implementation is to  arr1 operate on  filter , and for each element  item1, use  arr2.some traversal  arr2to find whether there is an element  item2, so that it can be  comparator(item1, item2) returned  true. If there is such an element  item2, it means that  it also exists item1 in  arr2 and should be filtered out; otherwise  it does not exist item1 in  arr2 and should be retained.

1.6: Test Cases
 

2. Handwritten drop function: drop(array,n=1)

1.1: function function

Creates a sliced ​​array, stripping arraythe first nelements. ( nThe default is 1.)

2.2: Parameter description

array (Array) : The array to query.

[n=1] (number) : The number of elements to remove.

2.3: return value

(Array) : Return arraythe remaining slice.

2.4: Implementation code

function drop(array, n = 1) {
  if (!Array.isArray(array)) {
    return []
  }
  return array.slice(n)
}

2.5: Implementation principle

It is to use the native slice slice function

2.6: Test Cases

 

3. Handwritten dropRight function: dropRight(array,n=1)

3.1: Function function

Creates a sliced ​​array, stripping arraytrailing nelements. ( nThe default is 1.)

3.2: Parameter description

array (Array) : The array to query.

[n=1] (number) : The number of elements to remove.

3.3: return value

(Array) : Return arraythe remaining slice.

3.4: Implementation code

function dropRight(array, n = 1) {
  if (!Array.isArray(array)) {
    return []
  }
  const length = array.length
  if (n >= length) {
    return []
  }
  return array.slice(0, length - n)
}

3.5: Implementation principle

The same is true for the use of the slice slice function

3.6: Test Cases

 

4. Handwritten dropRightWhile function: dropRightWhile(array,[predicate=._identity])

4.1: Function function

Create an array of slices, removing the part arrayfrom  predicate the return false value to the end. The predicate will pass in 3 parameters:  (value, index, array) . It means that the predicate parameter is a restriction, and slice processing is performed according to this restriction. It can be a function, object, array, string

4.2: Parameter description

array (Array) : The array to query.

[predicate=_.identity] (Function) : This function will be called on each iteration.

4.3: return value

(Array) : Return arraythe remaining slice.

4.4: Implementation code

function dropRightWhile(array, predicate) {
  const result = array.slice()
  let i = result.length - 1

  // 根据不同的参数类型构造相应的判定函数
  if (typeof predicate === 'function') {
    while (i >= 0 && predicate(result[i], i, result)) {
      result.pop()
      i--
    }
  } else if (Array.isArray(predicate)) {
    while (i >= 0 && result[i][predicate[0]] === predicate[1]) {
      result.pop()
      i--
    }
  } else if (typeof predicate === 'object') {
    const keys = Object.keys(predicate)
    while (i >= 0 && keys.every((key) => result[i][key] === predicate[key])) {
      result.pop()
      i--
    }
  } else if (typeof predicate === 'string') {
    while (i >= 0 && result[i][predicate]) {
      result.pop()
      i--
    }
  }

  return result
}

4.5: Implementation principle

  1. In the function, first copy the incoming array  arrayto avoid modifying the original array;
  2. Define a variable  that represents  the index of itraversing the array from right to left  , initialized to the index of the last element of the array;array
  3. According to the type of the assertion function  predicate , construct the corresponding conditional judgment to process different types of assertion functions;
  4. According to the array traversal, use the condition to judge the collection, judge whether the element meets the condition from the end, and delete the element if it meets the condition, until the first element that does not meet the condition is found;
  5. Returns a new array after removing eligible elements  result.

4.6: Test Cases

 Official test case:

 The function and implementation of the dropWhile function and dropRightWhile function are similar, the difference is that one cuts from the beginning and the other cuts from the end

5. Handwritten fill function: fill(array, value, start=0, end=array.length)

5.1: Function function

value Fill (replace)  with  values ​​starting arrayat startposition, endending at but not including endposition.

Note:  This method will change  array(note: instead of creating a new array).

5.2: Parameter description

array (Array) : The array to fill with changes.

value (*) : fill with  array the given value.

[start=0] (number) : The starting position (default 0).

[end=array.length] (number) : end position (default array.length).

5.3: Return value

(Array) : Returns  array.

5.4: Implementation code

function fill(array, value, start = 0, end = array.length) {
  for (let i = start; i < end; i++) {
    array[i] = value
  }
  return array
}

5.5: Implementation Principle

That is, the array can be looped through and replaced.

5.6: Test Cases

 

Guess you like

Origin blog.csdn.net/m0_64642443/article/details/131299655