Lodash源码解析一fill

253 阅读1分钟

_.fill

image.png

    /* 
     *
     * _.fill([4, 6, 8, 10], '*', 1, 3);  // 调用示例
     * // => [4, '*', '*', 10]
     */
function fill(array, value, start, end) {
    var length = array == null ? 0 : array.length;
    if (!length) {
        return [];
    }
    // 判断传值是否正确,数据为或者错误设置初始值,一般值不走这一步
    if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { 
      start = 0;
      end = length;
    }
    return baseFill(array = [4,6,8,10], value = '*', start = 1, end = 3); // 核心代码
  }

  function isIterateeCall(value, index, object) {
        if (!isObject(object)) {
            return false;
        }
        var type = typeof index;
        if (type == 'number'
                ? (isArrayLike(object) && isIndex(index, object.length))
                : (type == 'string' && index in object)
            ) {
            return eq(object[index], value);
            /* 
                function eq(value, other) {
                    return value === other || (value !== value && other !== other);
                }
            */
        }
            return false;
    }

    function baseFill(array = [4,6,8,10], value = '*', start = 1, end = 3) {
        var length = array.length;  // 4
  
        start = toInteger(start); // 转化为整数 1
        if (start < 0) {
          start = -start > length ? 0 : (length + start);
        }
        end = (end === undefined || end > length) ? length : toInteger(end); // 3
        if (end < 0) {
          end += length;
        }
        end = start > end ? 0 : toLength(end); // 3
        while (start < end) {
          array[start++] = value;
          /*
            array[1] = *
            array[2] = *
            结束
           */
        }
        return array; // [4,*,*,10]
      }

方法思路

  • 校验传值是否合规(lodash的老套路)
  • 不合规直接返回空数组,或者给初始值
  • 核心方法:确定开始位置和结束位置然后while循环,进行值的填充,最终抛出计算的值