I'm going through Immutable.js's source code and there's an ownerID
field that I don't understand.
Here's the source for Map.asMutable()
and Map.asImmutable()
: https://github.com/facebook/immutable-js/blob/master/src/Map.js#L171
It seems like the only difference between a mutable and an immutable object are their ownerID
s. What is an ownerID
and what is it used for?
An immutable value is one whose content cannot be changed without creating an entirely new value. In JavaScript, primitive values are immutable — once a primitive value is created, it cannot be changed, although the variable that holds it may be reassigned another value.
JavaScript strings are immutable. This means that once a string is created, it is not possible to modify it. String methods create new strings based on the content of the current string — for example: A substring of the original using substring() .
The object being frozen is said to be immutable because the entire object state (values and references to other objects) within the whole object is fixed. Note that strings, numbers, and booleans are always immutable and that Functions and Arrays are objects.
Numbers, for instance, are immutable because you can't change its value. For example, you can't literarily change the value of 7 to 8. That doesn't make sense. Instead, you can change the value stored in the variable x from 7 to 8.
If you track back the property:
L#14:
import { DELETE, SHIFT, SIZE, MASK, NOT_SET, CHANGE_LENGTH, DID_ALTER, OwnerID,
MakeRef, SetRef, arrCopy } from './TrieUtils'
in src/TrieUtils.js :
L#36:
// A function which returns a value representing an "owner" for transient writes
// to tries. The return value will only ever equal itself, and will not equal
// the return of any subsequent call of this function.
export function OwnerID() {}
It is some property they create like hash to represent a virtual owner.
It is used to ensure mutability in asMutable
returned instances. When asMutable
is invoked, it ensures an __ownerId
and returns the current instance back -
asMutable() {
return this.__ownerID ? this : this.__ensureOwner(new OwnerID());
}
Then any supported mutating operations return the current instance back, instead of creating a new instance with the changes (which is key for immutability).
E.g., here's how the "clear" method operates based on the presence of __ownerId
-
clear() {
if (this.size === 0) {
return this;
}
if (this.__ownerID) {
this.size = 0;
this._root = null;
this.__hash = undefined;
this.__altered = true;
return this;
}
return emptyMap();
}
Notice that when this.__ownerID is present, the method returns the current instance (thereby mutating itself). But when it is absent, it returns a new map for ensuring immutability.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With