admin管理员组文章数量:1201590
I would like to change a value at a key in a Map I have. Other than the fact that using update
will give me an error if the key I ask to update doesn't exist, what benefit is there (if any) to using update
over set
? I find set
to be significantly more concise/cleaner. In fact, based on the documentation one could (blindly) argue that set
is actually more efficient than update
since set
doesn't have to perform the get
for the updater
function.
I would like to change a value at a key in a Map I have. Other than the fact that using update
will give me an error if the key I ask to update doesn't exist, what benefit is there (if any) to using update
over set
? I find set
to be significantly more concise/cleaner. In fact, based on the documentation one could (blindly) argue that set
is actually more efficient than update
since set
doesn't have to perform the get
for the updater
function.
2 Answers
Reset to default 18update
is more powerful when your new value is the result of a transform of the current value:
const inc = (x) => (x + 1)
const m = Immutable.Map({a: 1, b: 2, c: 3})
m.update('b', inc) #=> {a: 1, b: 3, c: 3})
vs. with set
:
m.set('b', inc(m.get('b'))
This example is pretty trivial, but the pattern of applying transforms to your data in this way becomes more common when you start building your algorithms around your data (as in FP) instead of the other way around. I’ve done things before in a game like game.update('player', moveLeft)
.
If you know what the new value is, though, then just use set
as update(key, x => val)
is rather silly.
@MatthewHerbst said:
(...) was wondering if it was still good practice to use update or if set was fine
in his comment on @andrew-marshall's response
I don't think it is a question of good or bad practice.
From what i understand there are two different use cases:
- the value you set does NOT depend on the previous value : use
set
- the value you set depends on the previous value: use
update
So you I don't think you should always use set
over update
(or the other way around), I think you should use one or the other depending on your use case
本文标签: javascriptImmutablejs Map set vs updateStack Overflow
版权声明:本文标题:javascript - Immutable.js Map set vs update - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738631235a2103758.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论