Chapter 8. Flow-Based Programming
This chapter continues the discussion of functional style by showing how functions, together with purity and isolated change, can compose to offer a fairly fluent programming style. The idea of snapping functional blocks together will be discussed herein and demonstrated with relevant examples.
Chaining
If you recall, in the implementation of condition1 from Chapter 5, I
resorted to using the following lines of code:
// ...varerrors=mapcat(function(isValid){returnisValid(arg)?[]:[isValid.message];},validators);// ...
The reason for this bit of trickery was that while the final result needed to be an array of error strings, each intermediate step could be either an array of suberror messages or nothing at all. Another reason was that I wanted to combine disparate behaviors, each with different return types. It would be much easier to compose these behaviors if the return value of one was of a form agreeable to the input arguments to the other. Take, for example, the following code:
functioncreatePerson(){varfirstName="";varlastName="";varage=0;return{setFirstName:function(fn){firstName=fn;returnthis;},setLastName:function(ln){lastName=ln;returnthis;},setAge:function(a){age=a;returnthis;},toString:function(){return[firstName,lastName,age].join(' ');}};}createPerson().setFirstName("Mike").setLastName("Fogus").setAge(108).toString();//=> "Mike Fogus 108"
The “magic” that allows method ...
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