lodash框架中的chunk与drop函数源码逐行分析

lodash是一个工具库,跟underscore差很少数组

chunk函数的做用: 把一维数组,按照固定的长度分段成二维数组函数

如:工具

chunk( [ 10, 20, 30, 40 ], 2 )     结果:  [[10, 20], [ 30, 40 ]]
解释:把数组[ 10, 20, 30, 40] 按每2个元素分红一段, 一共分红2段
chunk( [ 10, 20, 30, 40 ], 3 )     结果: [[10, 20, 30], [40]]
解释:把数组[10, 20, 30, 40] 按每3个元素分红一段, 剩下的那个元素,独立做为一段
chunk( [ 10, 20, 30, 40 ], 1 )     结果: [[10],[20],[30],[40]]
解释:把数组[10, 20, 30, 40] 按每一个元素分红一段, 一共能够分红4段
 1         function chunk(array, size) {
 2             size = Math.max(size, 0);
 3             const length = array == null ? 0 : array.length;
 4             if (!length || size < 1) {
 5                 return [];
 6             }
 7             let index = 0;
 8             let resIndex = 0;
 9             const result = new Array(Math.ceil(length / size));
10 
11             while (index < length) {
12                 result[resIndex++] = array.slice(index, (index += size));
13             }
14             return result;
15         }

第2行: size=Math.max( size, 0 ); 获取0和size之间的较大值, 纵观整个函数, 通俗点讲就是,若是size是负数,把size变为0,其实整个函数 有个小bug, 那就是没有对size是否传递参数作判断,spa

若是这样用 chunk( [ 10, 20, 30 ] ) 这样会报错,由于size没有传,默认为undefined, 在第9行 length / size的时候就会报错,  因此我认为更加严谨的作法是在第二行代码之间,再加一句判断:code

size = ( typeof size === 'undefined' ) ? 0 : size;
 这样就算是size没有传递参数,也能够把他变为0
第3行: const length = array == null ? 0 : array.length;   用来判断是否传递的是空数组,若是是length = 0, 若是不是length就是数组的实际长度
第4行:
if (!length || size < 1) {
return [];
}
若是长度为0, 或者size < 1 就不用往下执行了, 直接返回一个空数组
 
第9行:
const result = new Array(Math.ceil(length / size));
这句话是整个分段数组功能中很关键的一句, 把一维数组根据size须要分红的段数算出来了,
如  [ 10, 20, 30, 40 ], 这个一维数组, length = 4,
若是size = 1, 就能够分红4段 [ [], [], [], [] ]
若是size = 2, 就能够分红2段 [ [], [] ]
若是size = 3, 仍是分红2段 [ [], [] ]
若是size = 4, 分红1段 [ [] ]
 
第11-13行就是 把具体的值 插入到对应的段
while (index < length) {
result[resIndex++] = array.slice(index, (index += size));
}
写法很是的精简,这段代码,若是我改为for循环,相信你应该很容易就能看懂
for( ; index < length; ) {
result[resIndex] = array.slice( index, index + size );
resIndex++;
index = index + size;
}
 正常状况须要3句,如今精简成一句。
 
 drop函数: 其实就是把slice封装了一次,其实lodash自己并非这么写的,在lodash中,slice被从新封装了一次,我把他改为原生slice用法,抽取出来,便于分析
 1         function drop(array, n = 1) {
 2             const length = array == null ? 0 : array.length;
 3             return length
 4                 ? array.slice( n < 0 ? 0 : n, length)
 5                 : [];
 6         }
 7 
 8         console.log( drop( [ 10, 20, 30 ] ) ); //[ 20, 30 ]
 9         console.log( drop( [ 10, 20, 30 ], 3 ) ); //[]
10         console.log( drop( [ 10, 20, 30 ], 2 ) ); //[30]
相关文章
相关标签/搜索