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

Table of contents

I. Introduction

1. What is lodash

2. The benefits of handwriting Lodash built-in functions 

2. Today's practice

1. Handwritten chunk function: chunk(array, size)

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 compact function: compact(array)

2.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 concat function: concat(array,value)

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 difference function: difference(array,value)

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 differenceBy function: differenceBy(array, value, fn)

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 place to practice after learning the syntax of Javascript and es6 , which will easily lead to the situation of forgetting after learning, and native Javascript is very important for front-end learners. 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 chunk function: chunk(array, size)

1.1: function function

Split the array  array  into  chunks of size  size and form these chunks into a new array. If  the array cannot be split into all blocks of equal length, then the last remaining elements will form a block.

1.2: Parameter description

array (Array) : the array to process

[size=1] (number) : the length of each array block

1.3: return value

(Array) : Return a new array containing split blocks (note: equivalent to a two-dimensional array).

1.4: Implementation code

function check(array, size) {
  // 如果需要划分的尺寸 size < 1,则直接返回空数组
  if (size < 1) return []
  const result = [] // 定义空数组,用于存放子数组
  // 使用循环,每次将数组按照 size 切割成一个个子数组
  for (let i = 0; i < array.length; i += size) {
    // 使用 slice 函数截取一个子数组,并将其添加到结果数组中
    result.push(array.slice(i, i + size))
  }
  return result
}

1.5: Implementation principle

Use the built-in method slice of array for positional cutting

1.6: Test Cases

2. Handwritten compact function: compact(array)

2.1: Function function

Creates a new array containing all non-false-valued elements in the original array. For example falsenull, 0""undefined, and  NaN are considered "false values".

2.2: Parameter description

array (Array) : the array to be processed

2.3: return value

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

2.4: Implementation code

function compact(array) {
  const result = []
  if (array == null) return []
  for (let i = 0; i < array.length; i++) {
    if (array[i]) result.push(array[i])
  }
  return result
}

2.5: Implementation principle

First judge whether the array is empty, and then traverse and add if judgment. The above "false values" cannot pass the if judgment

2.6: Test Cases

3. Handwritten concat function: concat(array,value)

3.1: Function function

Creates a new array that will arraybe concatenated with any array or value.

3.2: Parameter description

array (Array) : The array to be concatenated.

[value] (...*) : The concatenated value.

3.3: return value

(Array) : Returns the new concatenated array.

3.4: Implementation code

function concat(...array) {
  const result = []
  for (let i = 0; i < array.length; i++) {
    const arr = array[i]
    if (Array.isArray(arr)) {
      result.push(...arr) //这里使用的是es6的语法展开运算符
    } else {
      result.push(arr)
    }
  }
  return result
}


3.5: Implementation principle

The parameters here also use the syntax of es6, expand the operator to receive parameters and place them in an array, and then perform traversal processing. If it is an array, it will be expanded and opened into the original array, otherwise it will be directly pushed into the original array.

3.6: Test Cases

4. Handwritten difference function: difference(array,value)

4.1: Function function

Creates an arrayarray with unique values, each not contained in other given arrays. array (Note: That is, a new array is created, and the values ​​in this array exclude the values ​​in the given array for the first number ( parameter).)

4.2: Parameter description

array (Array) : Array to check.

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

4.3: return value

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

4.4: Implementation code

function difference(array, ...values) {
  // 声明一个空数组,用于存放结果
  const result = []
  // 将所有 values 参数展开组成一个大数组
  const valuesArray = []
  for (let i = 0; i < values.length; i++) {
    valuesArray.push(...values[i])
  }
  // 遍历 array 数组中的每个元素,判断是否在 valuesArray 数组中出现过
  for (let j = 0; j < array.length; j++) {
    // 在 valuesArray 中查找是否有与 array[j] 相等的元素
    let hasEqual = false
    for (let k = 0; k < valuesArray.length; k++) {
      if (array[j] === valuesArray[k]) {
        hasEqual = true
        break
      }
    }
    // 如果 array[j] 没有在任何 valuesArray 中出现过,则将其添加到 result 数组中
    if (!hasEqual) {
      result.push(array[j])
    }
  }
  return result
}


4.5: Implementation principle

Detailed comments are added to the code

4.6: Test Cases

5. Handwritten differenceBy function: differenceBy(array, value, fn)

5.1: Function function

This method is similar to difference  , but it adds a restriction that it can receive an iterator, similar to a function, but the parameter can also be a letter, an array, etc., and it filters the previous array according to the restriction of fn

5.2: Parameter description

array (Array) : Array to check.

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

[fn] (Array|Function|Object|string) : fn called for each element.

5.3: Return value

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

5.4: Implementation code

function differenceBy(arr1, arr2, iteratee) {
  const func = typeof iteratee === 'function' ? iteratee : (obj) => obj[iteratee]
  const values2 = new Set(arr2.map(func))
  return arr1.filter((item) => !values2.has(func(item)))
}


5.5: Implementation Principle 

First use  map the method to convert and add the elements in the second array to the Set object, then use  filter the method to filter the elements present in the Set object in the first array, and finally get the difference between the two arrays.

The map function is to process the array with the parameters passed in by func

For example:

const arr = ['hello', 'world', 'javascript'];
const newArr = arr.map(item => item.toUpperCase());
console.log(newArr); // ['HELLO', 'WORLD', 'JAVASCRIPT']

5.6: Test Cases

 Insist on writing five every day, after a period of time, your coding ability will definitely improve by leaps and bounds, come on

Guess you like

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