O'Reilly logo

Functional JavaScript by Michael Fogus

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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:

var rand = partial1(_.random, 1);

Using rand is as simple as the following:

rand(10);
//=> 7

repeatedly(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:

function randString(len) {
  var ascii = repeatedly(len,  partial1(rand, 26));

  return _.map(ascii, function(n) {
    return n.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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required