Javascript Allongé, the ``Six'' Edition
Total Page:16
File Type:pdf, Size:1020Kb
JavaScript Allongé, the “Six” Edition Programming from Functions to Classes in ECMAScript 2015 Reg “raganwald” Braithwaite This book is for sale at http://leanpub.com/javascriptallongesix This version was published on 2017-11-03 This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools and many iterations to get reader feedback, pivot until you have the right book and build traction once you do. © 2015 - 2017 Reg “raganwald” Braithwaite Also By Reg “raganwald” Braithwaite Kestrels, Quirky Birds, and Hopeless Egocentricity What I’ve Learned From Failure How to Do What You Love & Earn What You’re Worth as a Programmer Steal Raganwald’s Book! CoffeeScript Ristretto Contents A Pull of the Lever: Prefaces ................................... i About JavaScript Allongé ................................... ii What JavaScript Allongé is. And isn’t. ............................ v Foreword to the “Six” edition . viii Forewords to the First Edition ................................. ix About The Sample PDF .................................... xi Prelude: Values and Expressions over Coffee ......................... xiii values are expressions ..................................... xiv values and identity ....................................... xvi A Rich Aroma: Basic Numbers .................................. 1 The first sip: Basic Functions ................................... 5 As Little As Possible About Functions, But No Less ..................... 7 Ah. I’d Like to Have an Argument, Please. .......................... 16 Closures and Scope ...................................... 21 That Constant Coffee Craving ................................ 26 Naming Functions ....................................... 39 Combinators and Function Decorators ............................ 45 Building Blocks ........................................ 48 Magic Names .......................................... 51 Summary ............................................ 55 Recipes with Basic Functions .................................. 56 Partial Application ....................................... 57 Unary .............................................. 59 Tap ............................................... 61 Maybe ............................................. 63 Once .............................................. 65 Left-Variadic Functions .................................... 66 Picking the Bean: Choice and Truthiness ............................ 71 CONTENTS Composing and Decomposing Data ............................... 77 Arrays and Destructuring Arguments ............................ 78 Self-Similarity ......................................... 86 Tail Calls (and Default Arguments) .............................. 94 Garbage, Garbage Everywhere ................................103 Plain Old JavaScript Objects .................................109 Mutation ............................................118 Reassignment .........................................125 Copy on Write .........................................135 Tortoises, Hares, and Teleporting Turtles . 141 Functional Iterators ......................................144 Making Data Out Of Functions ................................154 Recipes with Data ......................................... 168 mapWith ............................................170 Flip ...............................................172 Object.assign ..........................................175 Why? ..............................................178 A Warm Cup: Basic Strings and Quasi-Literals ........................ 179 Served by the Pot: Collections .................................. 182 Iteration and Iterables .....................................183 Generating Iterables ......................................201 Lazy and Eager Collections ..................................223 Interlude: The Carpenter Interviews for a Job . 238 Interactive Generators .....................................250 Basic Operations on Iterables .................................261 The Golden Crema: Appendices and Afterwords ....................... 265 How to run the examples ...................................266 Thanks! .............................................268 Copyright Notice ........................................270 About The Author .......................................274 A Pull of the Lever: Prefaces Caffe Molinari “Café Allongé, also called Espresso Lungo, is a drink midway between an Espresso and Americano in strength. There are two different ways to make it. The first, and the one I prefer, is to add a small amount of hot water to a double or quadruple Espresso Ristretto. Like adding a splash of water to whiskey, the small dilution releases more of the complex flavours in the mouth. “The second way is to pull an extra long double shot of Espresso. This achieves approximately the same ratio of oils to water as the dilution method, but also releases a different mix of flavours due to the longer extraction. Some complain that the long pull is more bitter and detracts from the best character of the coffee, others feel it releases even more complexity. “The important thing is that neither method of preparation should use so much water as to result in a sickly, pale ghost of Espresso. Moderation in all things.” A Pull of the Lever: Prefaces ii About JavaScript Allongé JavaScript Allongé is a first and foremost, a book about programming with functions. It’s written in JavaScript, because JavaScript hits the perfect sweet spot of being both widely used, and of having proper first-class functions with lexical scope. If those terms seem unfamiliar, don’t worry: JavaScript Allongé takes great delight in explaining what they mean and why they matter. JavaScript Allongé begins at the beginning, with values and expressions, and builds from there to discuss types, identity, functions, closures, scopes, collections, iterators, and many more subjects up to working with classes and instances. It also provides recipes for using functions to write software that is simpler, cleaner, and less complicated than alternative approaches that are object-centric or code-centric. JavaScript idioms like function combinators and decorators leverage JavaScript’s power to make code easier to read, modify, debug and refactor. JavaScript Allongé teaches you how to handle complex code, and it also teaches you how to simplify code without dumbing it down. As a result, JavaScript Allongé is a rich read releasing many of JavaScript’s subtleties, much like the Café Allongé beloved by coffee enthusiasts everywhere. why the “six” edition? ECMAScript 2015 (formerly called ECMAScript 6 or “ES6”), is ushering in a very large number of improvements to the way programmers can write small, powerful components and combine them into larger, fully featured programs. Features like destructuring, block-structured variables, iterables, generators, and the class keyword are poised to make JavaScript programming more expressive. Prior to ECMAScript 2015, JavaScript did not include many features that programmers have dis- covered are vital to writing great software. For example, JavaScript did not include block-structured variables. Over time, programmers discovered ways to roll their own versions of important features. For example, block-structured languages allow us to write: for (int i = 0; i < array.length; ++i) { // ... } And the variable i is scoped locally to the code within the braces. Prior to ECMAScript 2015, JavaScript did not support block-structuring, so programmers borrowed a trick from the Scheme programming language, and would write: A Pull of the Lever: Prefaces iii var i; for (i = 0; i < array.length; ++i) { (function (i) { // ... })(i) } To create the same scoping with an Immediately Invoked Function Expression, or “IIFE.” Likewise, many programming languages permit functions to have a variable number of arguments, and to collect the arguments into a single variable as an array. In Ruby, we can write: def foo (first, *rest) # ... end Prior to ECMAScript 2015, JavaScript did not support collecting a variable number of arguments into a parameter, so programmers would take advantage of an awkward work-around and write things like: function foo () { var first = arguments[0], rest = [].slice.call(arguments, 1); // ... } The first edition of JavaScript Allongé explained these and many other patterns for writing flexible and composable programs in JavaScript, but the intention wasn’t to explain how to work around JavaScript’s missing features: The intention was to explain why the style of programming exemplified by the missing features is important. Working around the missing features was a necessary evil. But now, JavaScript is gaining many important features, in part because the governing body behind JavaScript has observed that programmers are constantly working around the same set of limitations. With ECMASCript 2015, we can write: for (let i = 0; i < array.length; ++i) { // ... } And i is scoped to the for loop. We can also write: A Pull of the Lever: Prefaces iv function foo (first, ...rest) { // ... } And presto, rest collects the rest of the arguments without a lot of malarky involving slicing arguments. Not having to work around these kinds of missing features makes JavaScript Allongé a better book, because it can focus on the why to do something and when to do it, instead of on the how to make it work JavaScript Allongé, The “Six” Edition packs all the goodness