/river.js Secret
Last active
August 29, 2015 14:13
JavaScript River Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Water molecules can still be Numbers | |
// since they're immutable values in JS | |
1 | |
2 | |
// The story is not so good with arrays | |
// JS Arrays are mutable by default | |
// and so we start with an identity | |
[1, 2, 3] | |
// As before, lets give this a name | |
var yellow_river = [1, 2, 3]; | |
// The identity can still have many names | |
var huang_he = yellow_river; | |
// var རྨ་ཆུ། = yellow_river; but tibetan doesn't work | |
// We're still missing our river value representation. | |
// Here's a snapshot function that extracts an | |
// immutable value from a mutable javascript array | |
function snapshot(array) { | |
return Object.freeze(array.slice()); | |
} | |
// Now we can extract the state at point in time from our river | |
snapshot(yellow_river); | |
// => [1, 2, 3] | |
// As before, a little trick to make our river flow | |
var timer = setInterval(function() { | |
yellow_river.forEach(function(v, i) { | |
yellow_river[i]++; | |
}); | |
}, 1000); | |
// And now as we look at the state of our river at different | |
// times, we see that the value has changed | |
snapshot(yellow_river); | |
// => [4, 5, 6] | |
// And we can still look via a different name | |
snapshot(huang_he); | |
// => [5, 6, 7] | |
// Now that we have all of the same tools, lets cross our river | |
var first_crossing = snapshot(yellow_river); | |
// And wait for a bit... | |
var d = Date.now(); while(Date.now() - d < 1200); | |
// Then cross it again | |
var second_crossing = snapshot(yellow_river); | |
// Now theres a slight problem - we made up our own | |
// representation of the river's value, so we have | |
// no way to compare the two crossing values. | |
// Let's write one: | |
function equal(a1, a2) { | |
return Object.isFrozen(a1) && | |
Object.isFrozen(a2) && | |
a1.every(function(v, i) { return v == a2[i] }); | |
} | |
// And as expected, our two values aren't the same | |
equal(first_crossing, second_crossing); | |
// => false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment