美文网首页
lodash源码分析-- chunk函数实现

lodash源码分析-- chunk函数实现

作者: shuta | 来源:发表于2018-06-29 12:07 被阅读0次

    _.chunk函数

    我的实现

    function chunk(array ,size) {
        if (!Array.isArray(array) || typeof size != 'number') {
            throw new TypeError('参数类型不正确')
        }
    
        let result = [];
        let groupResult = [];
        for (let i=0; i < array.length; i++) {
            groupResult.push(array[i]);
            if (i %size == size -1 || i == array.length -1) {
                result.push(groupResult);
                groupResult = []
            } 
    
        }
    
        return result
    }
    

    别人的实现

    function chunk(array, size) {
      size = Math.max(size, 0)
      const length = array == null ? 0 : array.length
      if (!length || size < 1) {
        return []
      }
      let index = 0
      let resIndex = 0
      const result = new Array(Math.ceil(length / size))
    
      while (index < length) {
        result[resIndex++] = slice(array, index, (index += size))
      }
      return result
    }
    

    对比

    1.我觉得这一次我的耗时应该比较少吧。哈哈哈哈哈,因为只循环了一遍数组
    2.但是有一点,result是可以先定义定长的数组。这一点是不是耗时比push操作耗时少?
    3.关于size的判断,我做得不是很好。这里需要学习。

    slice 函数

    我的实现

    function slice(array, start,end) {
        if (!Array.isArray(array)) {
            throw new TypeError('第一个参数必须是数组')
        }
    
        let len = array.length;
        if (start < 0) {
            start = -start > length ? 0: (start + length)
        }
    
        end = end > length ? length: end
        if (end < 0) {
            end = -end > length ? length : (end + length)
        }
    
        let result = []
    
        for (let index=start; index < end ; index++) {
            result.push(array[index])
        }
    
        return result
    }
    

    别人的实现

    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
    }
    

    1.>>>符号是?
    2.为了搞清楚push方法和loop中index方法,哪个效率高。我查了一下资料。只有一个说push(在chrome上的性能比array[i] 好)。其他都是array[i] 比push快(在重新定义array的情况下)

    参考文件
    https://stackoverflow.com/questions/21034662/why-push-method-is-significantly-slower-than-putting-values-via-array-indices-in
    https://stackoverflow.com/questions/614126/why-is-array-push-sometimes-faster-than-arrayn-value
    https://blog.scottlogic.com/2010/10/15/javascript-array-performance.html
    https://stackoverflow.com/questions/21034662/why-push-method-is-significantly-slower-than-putting-values-via-array-indices-in

    compact函数

    我的实现

    function compact(array) {
        let result = []
    
        for (let index=0; index < array.length; index++) {
            if(array[index]) {
                result.push(array[index])
            }
        }
    
        return result
    }
    
    compact([0,1,2,null,undefined,false,NaN])
    

    别人的实现

    function compact(array) {
      let resIndex = 0
      const result = []
    
      if (array == null) {
        return result
      }
    
      for (const value of array) {
        if (value) {
          result[resIndex++] = value
        }
      }
      return result
    }
    

    对比

    1.for ...of loop循环,只循环value。
    2.result[resIndex++] 来增加元素。

    _difference函数

    我的实现

    function notEqualValues(item, values) {
        return item != values
    }
    
    function notIncludeValues(item, array) {
        return !array.includes(item)
    }
    
    function difference(array,values) {
        if (!Array.isArray(array)) {
            throw new TypeError('第一个参数不是数组')
        }
    
        let judgeFn = Array.isArray(values) ? notIncludeValues : notEqualValues
    
    
        let result = []
        let index = 0
    
        for (let i=0; i < array.length;i++) {
            if (judgeFn.call(this, array[i], values)) {
                result[index++]  = array[i]
            }
        }
    
        return result
    }
    

    别人的实现

    我大概整理出来的实现如下所示:

    function isObjectLike(value) {
      return typeof value == 'object' && value !== null
    }
    
    function isLength(value) {
      return typeof value == 'number' &&
        value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER
    }
    
    function isArray(value) {
        return value !== null && typeof value != 'function' && isLength(value.length)
    }
    
    function flatternArray(values) {
        let result = [];
    
        for (value of values) {
            if (isObjectLike(value) && isArray(value)) {
                result.push(...value)
            }
        }
    
        return result
    }
    
    function lodashDifference(array, ...values) {
        let newValues = flatternArray(values);
        let valuesLength = newValues.length++;
    
    outer:
        for (let val of array) {
            let valuesIndex = valuesLength
             while (valuesIndex--) {
                if (newValues[valuesIndex] === val) {
                  continue outer
                }
            }
    
            result.push(value)
        }
    
        return result
    }
    

    总结:
    1.判断是否是数组,很奇怪。先判断是否是object,然后用length来判断是否是数组
    2.我实现的时候,以为第二个入参可以是value也可以是array。但是其实这个函数,第二个参数只能是array。lodash实现时就非常奇怪。它将array这个参数包裹成二维数组之后,然后再拉平成一维数组(为什么?)而且拉平的一维数组时,用了result.push(...value),我觉得这个技巧get到了。
    3.它用了outer ,看代码的用法时,退出第二层循环,但是不退出第一层循环。很好玩,我再查查.

    参考文档:
    https://stackoverflow.com/questions/183161/best-way-to-break-from-nested-loops-in-javascript

    相关文章

      网友评论

          本文标题:lodash源码分析-- chunk函数实现

          本文链接:https://www.haomeiwen.com/subject/blrbyftx.html