gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:11:10 25 4
gpt4 key购买 nike

我正在研究 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() 将返回一个 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 不会实际评估您的 map 函数,直到在某处使用了 mapped

关于javascript - ImmutableJS 会跳过未使用的代码块吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46125752/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com