每日源码分析 - Lodash(remove.js)

本系列使用 lodash 4.17.4版本

源码分析不包括引用文件分析

一、源码

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`, this method mutates `array`. 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 The function 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
复制代码

二、函数作用

函数引用示例:

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]
复制代码

从上面的例子可以看出:

  • remove 函数共有两个参数,即 array 和 predicate 。

  • array 参数传入的是一个数组,predicate 传入的是一个函数。

  • remove函数 的返回结果就是经 predicate 处理后为真的元素组成的数组,即被移除的元素组成的新数组。

  • 被相应移除元素后,array 数组由剩下的元素组成。

三、函数工作原理

  1. 判断参数合法性, 若数组 array 为空,则返回空数组 result;

    if (!(array != null && array.length)) {
        return result
    复制代码

} ```

  1. 遍历数组;
while (++index < length) {
    const value = array[index]
    if (predicate(value, index, array)) {
      result.push(value)
      indexes.push(index)
    }
  }
复制代码
  • 把由 predicate 过滤为真值的元素放入新数组 result 中;

  • 把遍历的索引 index 放入 indexs 中;

  1. 移除数组在 indexs 中对应索引的元素,并返回这些元素.
basePullAt(array, indexes)
复制代码

本文章来源于午安煎饼计划Web组 - 初见

相关链接:

每日源码分析 – lodash(chunk.js)

每日源码分析 – lodash(slice.js)

每日源码分析 - lodash(debounce.js和throttle.js)

每日源码分析-Lodash(drop.js)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值