关于lodash times.js的一些困惑

时间:2020-06-07 10:37:10

标签: javascript node.js frontend lodash

这是lodash的源代码:

const MAX_SAFE_INTEGER = 9007199254740991
const MAX_ARRAY_LENGTH = 4294967295
function times(n, iteratee) {
  if (n < 1 || n > MAX_SAFE_INTEGER) {
    return []
  }
  let index = -1
  const length = Math.min(n, MAX_ARRAY_LENGTH)
  const result = new Array(length)
  while (++index < length) {
    result[index] = iteratee(index)
  }
  index = MAX_ARRAY_LENGTH
  n -= MAX_ARRAY_LENGTH
  while (++index < n) {
    iteratee(index)
  }
  return result
}

我最困惑的是最后一部分:

index = MAX_ARRAY_LENGTH
  n -= MAX_ARRAY_LENGTH
  while (++index < n) {
    iteratee(index)
  }

我这样做的目的是确保iterateenn之间时,MAX_ARRAY_LENGTH调用MAX_SAFE_INTEGER次。

此时,代码应为:

while (++index < n) {
  iteratee(index)
}

所以为什么lodash让n -= MAX_ARRAY_LENGTH

这是功能还是错误?

0 个答案:

没有答案
相关问题