ImmutableJS 会跳过未使用的代码块吗?

Does ImmutableJS skip unused code block?

我正在研究 Immutable.js 代码,发现了一些奇怪的东西。 Immutable.js 是否跳过保存到不会使用的变量的代码?

const Immutable = require('immutable')

function transformErrors(errors) {
    let key = errors.keySeq()
    let mapped = key.map((v, keystr) => {
      console.log(v, keystr)
      return keystr
    })
  // If I enable the console log below, console log above works
  // console.log('mapped', mapped) 
};
const result = transformErrors(Immutable.fromJS([1, 2]));

对于上面的代码,如果

console.log('mapped', mapped)

被禁用,映射代码不会被调用。 我查看了文档,但找不到任何关于它的评论

行:let key = errors.keySeq() 将 return 一个 Seq 对象,在 immutable.js 中是惰性对象。

文档提供了以下详细信息 (https://facebook.github.io/immutable-js/docs/#/Seq):

Seq is lazy — Seq does as little work as necessary to respond to any method call. Values are often created during iteration, including implicit iteration when reducing or converting to a concrete data structure such as a List or JavaScript Array. For example, the following performs no work, because the resulting Seq's values are never iterated:

const { Seq } = require('immutable')
const oddSquares = Seq([ 1, 2, 3, 4, 5, 6, 7, 8 ])
  .filter(x => x % 2 !== 0)
  .map(x => x * x)

因此在您的示例中,immutable.js 不会实际评估您的地图函数,直到在某处使用 mapped