Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
919 views
in Technique[技术] by (71.8m points)

lodash times 函数的一点疑问,bug or feature?

先上源码:

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)
  }

我的理解是,如果 n 是在 MAX_ARRAY_LENGTHMAX_SAFE_INTEGER 之间的数字时,只有 0MAX_ARRAY_LENGTH 之间 iteratee 得到的结果会存入结果 result 中,但是 iteratee 还是会调用 n 次,只不过后面的结果会舍弃。

按照这个的理解,后半段应该是这样才对:

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

但是源码会将 n -= MAX_ARRAY_LENGTH ,即在 n - MAX_ARRAY_LENGTH 的结果比 MAX_ARRAY_LENGTH 还要大时,才会进行额外的 iteratee 调用。

所以这样做的目的是为什么呢?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

不对吧

index = MAX_ARRAY_LENGTH
n -= MAX_ARRAY_LENGTH
while (++index < n) {
    iteratee(index)
  }
 这段代码的意思是 n > 2 * MAX_ARRAY_LENGTH 才会额外执行吧。

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...