This series uses LoDash version 4.17.4
Source code analysis does not include reference file analysis
A, source
import basePullAt from './.internal/basePullAt.js'
/**
* Removes all elements from `array` that `predicate` returns truthy for* and returns an array of the removed elements. The predicate is invoked * with three arguments: (value, index, array). * * **Note:** Unlike `filter`, Use 'pull' * to pull elements from an array by value. * * @since 2.0.0 * @category array * @param {Array} array The array to modify. * @param {Function} predicate Thefunction invoked per iteration.
* @returns {Array} Returns the new array of removed elements.
* @see pull, pullAll, pullAllBy, pullAllWith, pullAt, reject, filter
* @example
*
* const array = [1, 2, 3, 4]
* const evens = remove(array, n => n % 2 == 0)
*
* console.log(array)
* // => [1, 3]
*
* console.log(evens)
* // => [2, 4]
*/
function remove(array, predicate) {
const result = []
if(! (array ! = null && array.length)) {return result
}
let index = -1
const indexes = []
const { length } = array
while (++index < length) {
const value = array[index]
if (predicate(value, index, array)) {
result.push(value)
indexes.push(index)
}
}
basePullAt(array, indexes)
return result
}
export default remove
Copy the code
Second, function function
Examples of function references:
var _= require('lodash');
//using remove.js
const array = [1, 2, 3, 4]
const evens = _.remove(array, n => n % 2 == 0)
console.log(array)
// => [1, 3]
console.log(evens)
// => [2, 4]
Copy the code
As can be seen from the above example:
-
The remove function takes two parameters, array and predicate.
-
The array argument is an array, the predicate is a function.
-
The result of the remove function is an array of the elements that are true after the predicate is processed, that is, a new array of the elements that have been removed.
-
The array array consists of the remaining elements that have been removed accordingly.
Three, function working principle
-
If array is empty, result is returned.
if(! (array ! = null && array.length)) {return result Copy the code
} ` ` `
- Traversal number group;
while (++index < length) {
const value = array[index]
if (predicate(value, index, array)) {
result.push(value)
indexes.push(index)
}
}
Copy the code
-
Place elements filtered to truth by predicate into a new array result;
-
Put the traversal index index into indexs;
- Removes the elements of the array corresponding to the index in indexs and returns those elements.
basePullAt(array, indexes)
Copy the code
This article is from the Good Afternoon Pancake Project Web group – First look
Related links:
Daily Source Code Analysis – Lodash (chunk.js)
Daily source Code Analysis — Lodash (Slice.js)
Daily source code Analysis – Lodash (debelas.js and throttle.js)
Daily source Code Analysis -Lodash (drop.js)