Consider the following example:
function add(x, y) { return x + y; }
var collection = Object.freeze([1, 2, 3, 4]);
var consumerA = collection; // expects steady data
var consumerB = collection; // requires the latest data
var updatedCollection = collection.concat(5);
consumerA.reduce(add, 0); // 10 (desired result)
consumerB.reduce(add, 0); // 10 (incorrect result, should be 15)
consumerA
operates with the immutable data it expects. What can be done in Javascript to ensure that consumerB
always accesses the latest data?
Please notice: Just deep copying consumerA
and treating collection
as mutable data isn't an option.
UPDATE: The example merely serves to illustrate the fundamental problem, which is caused by shared reference types: Some consumers (or reference holder) rely on immutable, others on mutable data. I'm looking for a proper change tracking mechanism that solves this problem without undermining the benefits of immutable data.
Maybe the term "change tracking" is too vague. With change tracking I mean a way for consumerB
to be informed about the change (push mechanism) or (more interesting) to be able to discover the change (pull mechanism). The latter would require that consumerB
somehow gets access to the updated collection.