前言
前端在开发中,编写逻辑代码是基操,很多小伙伴都会使用一些逻辑工具,比如vue和react框架自带的一些好用的API,但是这些框架始终无法让我们在业务代码脱身,此时Lodash就是很棒的一个逻辑代码库,而且大佬们一致推荐要学习他的逻辑实现思想。
所以,我打算把他掰开了学,一周至少分享三个方法
,督促自己的自觉性,一步步解析记录各个方法,最终使自己的编码水平得到提升同时,也和读者一起成长。
步骤
也没有过多的思路,就是按照Lodash文档里的每个方法说明,然后在源码文件找到对应源代码进行逐个解析。
话不多说,开始第一个方法
先来看第一个方法,我把源码给贴出来
// 所用变量和方法
nativeMax = Math.max //取最大值
nativeCeil = Math.ceil // 取整进一位
function toInteger(value) {
var result = toFinite(value), // 转换为10进制数字
remainder = result % 1;
return result === result ? (remainder ? result - remainder : result) : 0;
}
function toFinite(value) {
if (!value) {
return value === 0 ? value : 0;
}
value = toNumber(value);
if (value === INFINITY || value === -INFINITY) {
var sign = (value < 0 ? -1 : 1);
return sign * MAX_INTEGER;
}
return value === value ? value : 0;
}
=============》toInteger('3.2'); // 去掉小数取整
复制代码
主方法chunk
function chunk(array, size, guard) {
if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) {
size = 1;
// guard暂时不管,文档具体没有用到,主要用于没有传size的时候, 默认分割单位是1
// _.chunk([1,2,4,5]) ==> [[1],[2],[3],[4],[5]]
} else {
size = nativeMax(toInteger(size), 0);
// nativeMax , toInteger 详见代码
// 这一步是保证size的传值正确,在0 和最大值里面最大值取整,如果传的值为0以下的值,默认为0
}
var length = array == null ? 0 : array.length;
// 取得数组的长度
if (!length || size < 1) { // 如果数组长度和分割长度不符合,直接返回空退出
return [];
}
var index = 0,
resIndex = 0,
result = Array(nativeCeil(length / size)); // 向上取整 取除数 建立好标准位数的数组
while (index < length) {
// 该方法的核心代码=======
result[resIndex++] = baseSlice(array, index, (index += size));
// (原数组,初始0,赋值size第二次为size的值,第三次再加一次size的值,以此类推,直到大于length的值停止)
// 该方法的核心代码=======
}
return result;
}
复制代码
核心方法
function baseSlice(array, start, end) {
var index = -1,
length = array.length;
debugger
if (start < 0) { // 第一次调用为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;
var result = Array(length);
while (++index < length) {
result[index] = array[index + start]; // 合成新的数组推出去
}
return result;
}
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END