(no title)
graue | 12 years ago
var fooString = "foo";
var secondFooString = fooString;
secondFooString; // => "foo"
fooString = "bar";
secondFooString; // => "foo"
We set the variable fooString to point to a different string, but the original, underlying string hasn't changed. In JavaScript, we can think of a string as a value.This is not the case with arrays in JavaScript:
var firstArray = [1, 2, 3];
var secondArray = firstArray;
firstArray[0] = 100;
firstArray; // => [100, 2, 3]
secondArray; // => also [100, 2, 3]
Because we can change the underlying contents of the array, an array in JavaScript isn't a value. It's a place: a reference to a location in memory. The underlying value could be changed at any time.But, using Mori, collections are values, just like strings:
var firstVec = m.vector(1, 2, 3);
var secondVec = firstVec;
firstVec = m.assoc(firstVec, 0, 100);
firstVec; // => [100, 2, 3]
secondVec; // => still [1, 2, 3]
Instead of modifying firstVec in place, mori.assoc creates a new vector that is identical to firstVec except for the change we want. We then assign the result to firstVec. secondVec is unchanged. We are unable to go in and change the underlying values because a vector is a value, not a place.The most obvious way to build this would be to deep-copy the entire collection when it's changed, but that would of course be way too slow and wasteful — imagine copying a one-million-long array just to change one element. Clojure, ClojureScript and Mori minimize unnecessary copying using a very thoughtfully designed data structure you can read about here: http://hypirion.com/musings/understanding-persistent-vector-... The short story is that, surprisingly, you get "effectively O(1)" copying when you use assoc.
No comments yet.