Lodash进修笔记 - slice函数

百忙之中(闲来无事)想抽点时候好好读一下源码,于是就选了Lodash来写一个系列罢。读源码递次就根据loadsh文档递次来。

文档地点:中文文档   英文文档
源码地点:gayhub

第一个函数是chunk,不过源码中chunk依靠了slice,所以第一篇文章就从slice最先。

    _.slice(array, [start=0], [end=array.length])

这个函数的作用就是裁剪数组array,从start下标最先,到end下标完毕,然则并不包括end,并将效果作为一个数组返回。而且注清楚明了:

Note: 这个要领用于替代
Array#slice 来确保数组准确返回。

看起来和原生javascript的slice没有区分,那为何要重写这个函数呢?有以下几个缘由:

  1. 比原生slice更快,测试地点,效果如图:《Lodash进修笔记 - slice函数》
  2. 有更好的兼容性,IE < 9 时没法转化伪数组对象(比方DOM),出处

下面我们来看一下详细的完成,一行行来看代码:

  • 首先是数组array是不是正当的推断:

    let length = array == null ? 0 : array.length
    if (!length) {
        return []
    }
  • 最先位置start和完毕位置end默认值:

    start = start == null ? 0 : start
    end = end === undefined ? length : end
  • 支撑负数start,以及start正当性检测:超越数组长度即为0,否则从右往左数

    if (start < 0) {
        start = -start > length ? 0 : (length + start)
    }
  • end正当性检测:超越数组长度即为数组长度
    假如end为负数,则从右往左数

    end = end > length ? length : end
    if (end < 0) {
        end += length
    }
  • 数组裁剪后的长度,这里为了速率所以使用了>>>来向下取整
    start向下取整

    length = start > end ? 0 : ((end - start) >>> 0)
    start >>>= 0
  • 经由过程轮回来浅拷贝数组的元素,终究返回

    let index = -1
    const result = new Array(length)
    while (++index < length) {
        result[index] = array[index + start]
    }
    return result

末了贴个源码:

/**
 * Creates a slice of `array` from `start` up to, but not including, `end`.
 *
 * **Note:** This method is used instead of
 * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are
 * returned.
 *
 * @since 3.0.0
 * @category Array
 * @param {Array} array The array to slice.
 * @param {number} [start=0] The start position. A negative index will be treated as an offset from the end. 
 * @param {number} [end=array.length] The end position. A negative index will be treated as an offset from the end. 
 * @returns {Array} Returns the slice of `array`.
 */
function slice(array, start, end) {
  let length = array == null ? 0 : array.length
  if (!length) {
    return []
  }
  start = start == null ? 0 : start
  end = end === undefined ? length : end

  if (start < 0) {
    start = -start > length ? 0 : (length + start)
  }
  end = end > length ? length : end
  if (end < 0) {
    end += length
  }
  length = start > end ? 0 : ((end - start) >>> 0)
  start >>>= 0

  let index = -1
  const result = new Array(length)
  while (++index < length) {
    result[index] = array[index + start]
  }
  return result
}

export default slice

《Lodash进修笔记 - slice函数》

    原文作者:我有一只小腊肠
    原文地址: https://segmentfault.com/a/1190000013703023
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞