Chapter 7. Purity, Immutability, and Policies for Change
This chapter marks the point when a fully functional and practical style is explored. Functional programming is not just about functions; it’s also a way of thinking about how to build programs to minimize the complexities inherent in the creation of software. One way of reducing the complexity is to reduce or eliminate (ideally) the footprint of state change taking place in our programs.
Purity
Imagine that you needed a function that, when given a number,
returned a (pseudo) random number greater than 0 and up to and including the number itself.
Underscore’s _.random function is
almost correct, but it defaults to including zero. Therefore, as a first
approximation, you might write something like this:
varrand=partial1(_.random,1);
Using rand is as simple as the
following:
rand(10);//=> 7repeatedly(10,partial1(rand,10));//=> [2, 6, 6, 7, 7, 4, 4, 10, 8, 5]_.take(repeatedly(100,partial1(rand,10)),5);//=> [9, 6, 6, 4, 6]
You can use rand as the basis for
a generator for random lowercase ASCII strings-with-numbers of a certain
length as follows:
functionrandString(len){varascii=repeatedly(len,partial1(rand,26));return_.map(ascii,function(n){returnn.toString(36);}).join('');}
And here’s the use of randString:
randString(0);//=> ""randString(1);//=> "f"randString(10);//=> "k52k7bae8p"
Building the randString function is just like what I’ve shown throughout the course of this book. Plugging functions into ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access