Open
Description
What happened
We cant create class which will work with functional get
, getIn
. Ok we can by extending our class with immutable base to make it pass isImmutable
but if our class is not 100% "isImmutable" compatible... Is this intentional?
import { get } from 'immutable';
class TestCollection {
constructor() {
this._root = { 'fizz': 'buz' };
this.other = 'yeah';
};
get(key) { return this._root[key] }
}
let test = new TestCollection()
get(test, 'fizz') // undefined
get(test, 'other') // undefined
Also implementation of get is a little bit convoluted, making me think that this limitation was not intentional.
Let check get and has (has
is only only used by get
). What makes it not work with es6 Map collection :(
// get
return isImmutable(collection)
? collection.get(key, notSetValue)
: !has(collection, key) // [1]
? notSetValue // [2]
: typeof collection.get === 'function' // [3]
? collection.get(key) // [4]
: collection[key];
- [1] not immutable then check if immutable again or is it Array of plain object with
key
property - [2] ok its not immutable (no surprise) nor is it plain object or Array with
key
property - [3] but then we check for
get
method in plain object or Array ? - [4] so this will only happen for
key='x'
and collection like{ [key]: ':]', get() { return ':O'} }
and I don't think this is intentional. ( this would returnget(collection, key) // :O
)
Solution ?
If get should work with class collections implementing get
method then we can do something like this:
export function get(collection, key, notSetValue) {
return isImmutable(collection)
? collection.get(key, notSetValue)
: typeof collection.get === 'function'
? collection.get(key, notSetValue)
: hasOwnProperty.call(collection, key)
? collection[key]
: notSetValue;
}