Immutable-js: Map#update() not respecting notSetValue

Created on 2 Oct 2015  路  3Comments  路  Source: immutable-js/immutable-js

I'm trying to set a value for a particular key in a map, but only if the key doesn't yet exist. To do this, I'm calling update and supplying a notSetValue.

var defaultVal = 'DEFAULT!~';
var m = Immutable.Map();

// approach A
if (!m.get('testkey')) {
  m = m.set('testkey', defaultVal);
}

// approach B
m = m.update('testkey', defaultVal, val => val);

My understanding is that A and B should do the same thing. When logging in B's updater function, I confirm that I receive the correct value for defaultVal but the value remains undefined.

Most helpful comment

(Please ignore those commits above. I went off half-cocked before I stopped and investigated the history of this change.)

If the update/updateIn method worked the way you inferred (correctly, IMHO) from the docs, this test would fail: https://github.com/facebook/immutable-js/blob/master/__tests__/updateIn.ts#L142

That test was added in commit https://github.com/facebook/immutable-js/commit/335b312 whose commit message explains the rationale.

In the interim until an official dev pokes their head in here, you can accomplish what you wish with m.update('testkey', (val = defaultVal) => val).

All 3 comments

(Please ignore those commits above. I went off half-cocked before I stopped and investigated the history of this change.)

If the update/updateIn method worked the way you inferred (correctly, IMHO) from the docs, this test would fail: https://github.com/facebook/immutable-js/blob/master/__tests__/updateIn.ts#L142

That test was added in commit https://github.com/facebook/immutable-js/commit/335b312 whose commit message explains the rationale.

In the interim until an official dev pokes their head in here, you can accomplish what you wish with m.update('testkey', (val = defaultVal) => val).

thanks, that makes sense. I think your approach reads nicely, but maybe we should include it in the docs because it's not obvious to try it that way.

I agree with @jbonta. I faced the same behaviour and was surprised that it's correct. Would be nice to see such case in documentation

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Daniel15 picture Daniel15  路  4Comments

jamesgpearce picture jamesgpearce  路  4Comments

s-panferov picture s-panferov  路  4Comments

NullDivision picture NullDivision  路  4Comments

sljuka picture sljuka  路  3Comments