Tải bản đầy đủ (.pdf) (635 trang)

JavaScript functional programming for javascript developers unlock the powers of functional programming hidden within javascript to build smarter, cleaner, and more realiable web apps

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (4.7 MB, 635 trang )


JavaScript: Functional
Programming for
JavaScript Developers
Unlock the powers of functional programming hidden
within JavaScript to build smarter, cleaner,
and more reliable web apps

A course in three modules

BIRMINGHAM - MUMBAI


JavaScript: Functional Programming for
JavaScript Developers
Copyright © 2016 Packt Publishing

All rights reserved. No part of this course may be reproduced, stored in a retrieval
system, or transmitted in any form or by any means, without the prior written
permission of the publisher, except in the case of brief quotations embedded in
critical articles or reviews.
Every effort has been made in the preparation of this course to ensure the accuracy
of the information presented. However, the information contained in this course
is sold without warranty, either express or implied. Neither the authors, nor Packt
Publishing, and its dealers and distributors will be held liable for any damages
caused or alleged to be caused directly or indirectly by this course.
Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this course by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.

Published on: August 2016



Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78712-466-0
www.packtpub.com


Credits
Authors
Ved Antani

Content Development Editor
Pooja Mhapsekar

Simon Timms
Dan Mantyla
Reviewers
Ivano Malavolta
Dobrin Ganev
Dom Derrien
Joe Dorocak
Peter Ehrlich
Edward E. Griebel Jr.

Graphics
Disha Haria
Production Coordinator
Aparna Bhagat




Preface
Functional programming is a style that emphasizes and enables smarter code that
minimizes complexity and increases modularity. It's a way of writing cleaner code
through clever ways of mutating, combining and using functions. And JavaScript
provides an excellent medium for this approach. JavaScript, the internet's scripting
language, is actually a functional language at heart. By learning how to expose
JavaScript's true identity as a functional language, we can implement web apps that
are more powerful, easier to maintain and more reliable. JavaScript's odd quirks and
pitfalls will suddenly become clear and the language as a whole will make infinitely
more sense. Learning how to use functional programming will make you a better
programmer for life.
This course is a guide for both new and experienced JavaScript developers who are
interested in learning functional programming. With a focus on the progression of
functional programming techniques and styles in JavaScript, detailed information
of JavaScript libraries, this course will help you to write smarter code and become a
better programmer.

What this learning path covers

Module 1, Mastering JavaScript, provides a detailed overview of the language
fundamentals and some of the modern tools and libraries – like jQuery,
underscore.js and jasmine.
Module 2, Mastering JavaScript Design Patterns- Second Edition, is divided into two
main parts. The first part covers the classical design patterns, which are found in the
GoF book whereas the second part looks at patterns, which are either not covered in
the GoF book or ones that are more specific to JavaScript.
Module 3, Functional Programming in JavaScript, explores the core concepts of

functional programming common to all functional languages, with examples
of their use in JavaScript.
[i]


Preface

What you need for this learning path

All the examples in this course can be run on any of the modern browsers. For the
last chapter from first module, you will need Node.js. You will need the following to
run the examples and samples from this course:
• A computer with Windows 7 or higher, Linux or Mac OSX installed
• Latest version of Google Chrome or Mozilla Firefox browser
• A texteditor of your choice. Sublime Text, Vi, Atom or Notepad++ would be
ideal. The choice is entirely yours.
There are standalone JavaScript engines written in C++ (V8) and Java (Rhino)
and these are used to power all sorts of tools such as nodejs, couchdb and even
elasticsearch. These patterns can be applied to any of these technologies.

Who this learning path is for

If you are a JavaScript developer interested in learning functional programming,
looking for the quantum leap towards mastering the JavaScript language, or just
want to become a better programmer in general, then this course is ideal for you.
This guide is aimed at programmers, involved in developing reactive front-end apps,
server-side apps that wrangle with reliability and concurrency, and everything
in between.

Reader feedback


Feedback from our readers is always welcome. Let us know what you think about
this course—what you liked or disliked. Reader feedback is important for us as it
helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail , and mention
the course's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing
or contributing to a book, see our author guide at www.packtpub.com/authors.

[ ii ]


Preface

Customer support

Now that you are the proud owner of a Packtproduct, we have a number of things to
help you to get the most from your purchase.

Downloading theexample code

You can download the example code files for this course from your account at
. If you purchased this course elsewhere, you can visit
and register to have the files e-mailed directly
to you.
You can download the code files by following these steps:
1. Log in or register to our website using your e-mail address and password.
2. Hover the mouse pointer on the SUPPORT tab at the top.
3. Click on Code Downloads & Errata.
4. Enterthe name of the course in the Search box.

5. Select the course for which you're looking to download the code files.
6. Choose from the drop-down menu where you purchased this course from.
7. Click on Code Download.
You can also download the code files by clicking on theCode Filesbutton on the
course's webpage at the Packt Publishing website. This page can be accessed by
entering the course's name in the Search box. Please note that you need to be
logged into your Packt account.
Once the file is downloaded, please make sure that you unzip or extract the folder
using the latest version of:
• WinRAR / 7-Zip for Windows
• Zipeg / iZip / UnRarX for Mac
• 7-Zip / PeaZip for Linux
The code bundle for the course is also hosted on GitHub at />
PacktPublishing/JavaScript--Functional-Programming-for-JavaScriptDevelopers.We also have other code bundles from our rich catalog of books, courses
and videos available at Check them out!

[ iii ]


Preface

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes
do happen. If you find a mistake in one of our courses—maybe a mistake in the text
or the code—we would be grateful if you could report this to us. By doing so, you
can save other readers from frustration and help us improve subsequent versions
of this course. If you find any errata, please report them by visiting http://www.
packtpub.com/submit-errata, selecting your course, clicking on the Errata
Submission Form link, and entering the details of your errata. Once your errata are

verified, your submission will be accepted and the errata will be uploaded to our
website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to />content/support and enter the name of the coursein the search field. The required
information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all
media. At Packt, we take the protection of our copyright and licenses very seriously.
If you come across any illegal copies of our works in any form on the Internet, please
provide us with the location address or website name immediately so that we can
pursue a remedy.
Please contact us at with a link to the suspected
pirated material.
We appreciate your help in protecting our authors and our ability to bring you
valuable content.

Questions

If you have a problem with any aspect of this course, you can contact us at
, and we will do our best to address the problem.

[ iv ]


Module 1: Mastering JavaScript
Chapter 1: JavaScript Primer

3


A little bit of history
4
How to use this book
5
Hello World
8
Summary45

Chapter 2: Functions, Closures, and Modules

47

Chapter 3: Data Structures and Manipulation

77

A function literal
48
Functions as data
51
Scoping52
Function declarations versus function expressions
60
The arguments parameter
62
Anonymous functions
66
Closures68
Timers and callbacks
71

Private variables
71
Loops and closures
72
Modules73
Summary75
Regular expressions
78
Exact match
79
Match from a class of characters
79
Repeated occurrences
83
Beginning and end
86
Backreferences86
Greedy and lazy quantifiers
87
Arrays88
Maps97
Sets97
A matter of style
99
Summary99
i


Table of Contents


Chapter 4: Object-Oriented JavaScript

101

Chapter 5: Testing and Debugging

123

Chapter 6: ECMAScript 6

141

Chapter 7: DOM Manipulation and Events

159

Chapter 8: Server-Side JavaScript

179

Understanding objects
101
Instance properties versus prototype properties
106
Inheritance112
Getters and setters
119
Summary122
Unit testing
124

JavaScript debugging
132
Summary140
Shims or polyfills
142
Transpilers142
ES6 syntax changes
143
Summary157

DOM159
Chaining169
Traversal and manipulation
169
Working with browser events
171
Propagation172
jQuery event handling and propagation
173
Event delegation
176
The event object
177
Summary178
An asynchronous evented-model in a browser
180
Callbacks184
Timers188
EventEmitters189
Modules190

npm193
JavaScript performance
196
Summary200

ii


Table of Contents

Module 2: Mastering JavaScript Design
Patterns - Second Edition
Chapter 1: Designing for Fun and Profit

203

Chapter 2: Organizing Code

219

Chapter 3: Creational Patterns

239

Chapter 4: Structural Patterns

259

The road to JavaScript
203

What is a design pattern?
211
Anti-patterns214
Summary215
Chunks of code
219
What's the matter with global scope anyway?
222
Objects in JavaScript
223
Build me a prototype
227
Inheritance230
Modules232
ECMAScript 2015 classes and modules
236
Best practices and troubleshooting
237
Summary237
Abstract factory
240
Builder247
Factory method
250
Singleton254
Prototype256
Tips and tricks
257
Summary258
Adapter260

Bridge264
Composite267
Decorator272
Façade274
Flyweight276
Proxy278
Hints and tips
281
Summary281

iii


Table of Contents

Chapter 5: Behavioral Patterns

283

Chapter 6: Functional Programming

323

Chapter 7: Reactive Programming

341

Chapter 8: Application Patterns

351


Chain of responsibility
284
Command288
Interpreter292
Iterator294
Mediator297
Memento299
Observer302
State305
Strategy308
Template method
312
Visitor315
Hints and tips
319
Summary320
Functional functions are side-effect-free
324
Function passing
324
Filters and pipes
328
Accumulators331
Memoization333
Immutability335
Lazy instantiation
337
Hints and tips
339

Summary339
Application state changes
342
Streams342
Filtering streams
345
Merging streams
347
Streams for multiplexing
349
Hints and tips
349
Summary350

First, some history
352
Model View Controller
352
Model View Presenter
361
Model View ViewModel
365
Tips and tricks
371
Summary371
iv


Table of Contents


Chapter 9: Web Patterns

373

Chapter 10: Messaging Patterns

393

Sending JavaScript
373
Plugins379
Doing two things at once – multithreading
384
Circuit breaker pattern
386
Promise pattern
389
Hints and tips
391
Summary392
What's a message anyway?
394
Request-reply398
Publish-subscribe401
Dead letter queues
407
Hints and tips
412
Summary412


Chapter 11: Microservices415

Façade417
Service selector
418
Aggregate services
419
Pipeline420
Message upgrader
421
Failure patterns
422
Hints and tips
425
Summary425

Chapter 12: Patterns for Testing

427

The testing pyramid
427
Testing in the small with unit tests
428
Arrange-Act-Assert430
Fake objects
431
Test spies
433
Stubs434

Mock436
Monkey patching
437
Interacting with the user interface
437
Tips and tricks
440
Summary441

v


Table of Contents

Chapter 13: Advanced Patterns

443

Chapter 14: ECMAScript-2015/2016 Solutions Today

455

Dependency injection
443
Live post processing
446
Aspect oriented programming
448
Mixins451
Macros452

Tips and tricks
453
Summary454
TypeScript455
BabelJS459
Tips and tricks
466
Summary467

Module 3: Functional Programming in JavaScript
Chapter 1: The Powers of JavaScript's Functional
Side – a Demonstration

471

Chapter 2: Fundamentals of Functional Programming

479

Chapter 3: Setting Up the Functional Programming Environment

507

Introduction471
The demonstration
472
The application – an e-commerce website
472
Functional programming
474

Summary477
Functional programming languages
479
Working with functions
487
The functional programmer's toolkit
497
Summary505
Introduction507
Functional libraries for JavaScript
508
Development and production environments
518
Summary522

vi


Table of Contents

Chapter 4: Implementing Functional Programming Techniques
in JavaScript

523

Chapter 5: Category Theory

547

Chapter 6: Advanced Topics and Pitfalls in JavaScript


569

Chapter 7: Functional and Object-oriented Programming
in JavaScript

589

Partial function application and currying
524
Function composition
532
Mostly functional programming
538
Functional reactive programming
541
Summary545
Category theory
548
Functors553
Monads557
Implementing categories
565
Summary568

Recursion570
Variable scope
579
Function declarations versus function expressions versus the
function constructor

584
Summary587

JavaScript – the multi-paradigm language
590
JavaScript's object-oriented implementation – using prototypes
591
Mixing functional and object-oriented programming in JavaScript
595
Summary603

Appendix A: Common Functions for Functional Programming
in JavaScript
605
Appendix B: Glossary of Terms
613
Bibliography617

vii



Module 1

Mastering JavaScript
Explore and master modern JavaScript techniques in order to build large-scale
web applications




JavaScript Primer
It is always difficult to pen the first few words, especially on a subject like JavaScript.
This difficulty arises primarily because so many things have been said about this
language. JavaScript has been the Language of the Web—lingua franca, if you will,
since the earliest days of the Netscape Navigator. JavaScript went from a tool of the
amateur to the weapon of the connoisseur in a shockingly short period of time.
JavaScript is the most popular language on the web and open source ecosystem.
o/ charts the number of active repositories and overall
popularity of the language on GitHub for the last few years. JavaScript's popularity
and importance can be attributed to its association with the browser. Google's V8
and Mozilla's SpiderMonkey are extremely optimized JavaScript engines that power
Google Chrome and Mozilla Firefox browsers, respectively.
Although web browsers are the most widely used platforms for JavaScript, modern
databases such as MongoDB and CouchDB use JavaScript as their scripting and
query language. JavaScript has become an important platform outside browsers
as well. Projects such as Node.js and io.js provide powerful platforms to develop
scalable server environments using JavaScript. Several interesting projects are
pushing the language capabilities to its limits, for example, Emscripten (http://
kripken.github.io/emscripten-site/) is a Low-Level Virtual Machine (LLVM)based project that compiles C and C++ into highly optimizable JavaScript in an asm.
js format. This allows you to run C and C++ on the web at near native speed.
JavaScript is built around solid foundations regarding, for example, functions,
dynamic objects, loose typing, prototypal inheritance, and a powerful object
literal notation.

[3]


JavaScript Primer

While JavaScript is built on sound design principles, unfortunately, the language

had to evolve along with the browser. Web browsers are notorious in the way
they support various features and standards. JavaScript tried to accommodate all
the whims of the browsers and ended up making some very bad design decisions.
These bad parts (the term made famous by Douglas Crockford) overshadowed the
good parts of the language for most people. Programmers wrote bad code, other
programmers had nightmares trying to debug that bad code, and the language
eventually got a bad reputation. Unfortunately, JavaScript is one of the most
misunderstood programming languages ( />javascript.html).
Another criticism leveled at JavaScript is that it lets you get things done without
you being an expert in the language. I have seen programmers write exceptionally
bad JavaScript code just because they wanted to get the things done quickly and
JavaScript allowed them to do just this. I have spent hours debugging very bad
quality JavaScript written by someone who clearly was not a programmer. However,
the language is a tool and cannot be blamed for sloppy programming. Like all crafts,
programming demands extreme dedication and discipline.

A little bit of history

In 1993, the Mosaic browser of National Center for Supercomputing Applications
(NCSA) was one of the first popular web browsers. A year later, Netscape
Communications created the proprietary web browser, Netscape Navigator. Several
original Mosaic authors worked on Navigator.
In 1995, Netscape Communications hired Brendan Eich with the promise of letting
him implement Scheme (a Lisp dialect) in the browser. Before this happened,
Netscape got in touch with Sun Microsystems (now Oracle) to include Java in the
Navigator browser.
Due to the popularity and easy programming of Java, Netscape decided that a
scripting language had to have a syntax similar to that of Java. This ruled out
adopting existing languages such as Python, Tool Command Language (TCL), or
Scheme. Eich wrote the initial prototype in just 10 days (puter.

org/csdl/mags/co/2012/02/mco2012020007.pdf), in May 1995. JavaScript's
first code name was Mocha, coined by Marc Andreessen. Netscape later changed
it to LiveScript, for trademark reasons. In early December 1995, Sun licensed the
trademark Java to Netscape. The language was renamed to its final name, JavaScript.

[4]


Chapter 1

How to use this book

This book is not going to help if you are looking to get things done quickly. This
book is going to focus on the correct ways to code in JavaScript. We are going to
spend a lot of time understanding how to avoid the bad parts of the language and
build reliable and readable code in JavaScript. We will skirt away from sloppy
features of the language just to make sure that you are not getting used to them—if
you have already learned to code using these habits, this book will try to nudge you
away from this. There will be a lot of focus on the correct style and tools to make
your code better.
Most of the concepts in this book are going to be examples and patterns from realworld problems. I will insist that you code each of the snippets to make sure that your
understanding of the concept is getting programmed into your muscle memory. Trust
me on this, there is no better way to learn programming than writing a lot of code.
Typically, you will need to create an HTML page to run an embedded JavaScript
code as follows:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript">

var x = "Hello World";
console.log(x);
</script>
</head>
<body>
</body>
</html>

This sample code shows two ways in which JavaScript is embedded into the HTML
page. First, the <script> tag in <head> imports JavaScript, while the second
<script> tag is used to embed inline JavaScript.
Downloading the example code
You can download the example code files from your account at
for all the Packt Publishing books you
have purchased. If you purchased this book elsewhere, you can visit
and register to have the files
e-mailed directly to you.

[5]


JavaScript Primer

You can save this HTML page locally and open it in a browser. On Firefox, you can
open the Developer console (Firefox menu | Developer | Web Console) and you
can see the "Hello World" text on the Console tab. Based on your OS and browser
version, the screen may look different:

You can run the page and inspect it using Chrome's Developer Tool:


A very interesting thing to notice here is that there is an error displayed on the
console regarding the missing .js file that we are trying to import using the
following line of code:
<script type="text/javascript" src="script.js"></script>

Using browser developer consoles or an extension such as Firebug can be very useful
in debugging error conditions in the code. We will discuss in detail the debugging
techniques in later chapters.
Creating such HTML scaffolds can be tedious for every exercise in this book. Instead,
we want to use a Read-Eval-Print-Loop (REPL) for JavaScript. Unlike Python,
JavaScript does not come packaged with an REPL. We can use Node.js as an REPL. If
you have Node.js installed on your machine, you can just type node on the command
line and start experimenting with it. You will observe that Node REPL errors are not
very elegantly displayed.

[6]


Chapter 1

Let's see the following example:
EN-VedA:~$ node
>function greeter(){
x="World"l
SyntaxError: Unexpected identifier
at Object.exports.createScript (vm.js:44:10)
at REPLServer.defaultEval (repl.js:117:23)
at bound (domain.js:254:14)



After this error, you will have to restart. Still, it can help you try out small fragments
of code a lot faster.
Another tool that I personally use a lot is JS Bin ( JS Bin
provides you with a great set of tools to test JavaScript, such as syntax highlighting
and runtime error detection. The following is a screenshot of JS Bin:

Based on your preference, you can pick the tool that makes it easier to try out the
code samples. Regardless of which tool you use, make sure that you type out every
exercise in this book.

[7]


JavaScript Primer

Hello World

No programming language should be published without a customary Hello World
program—why should this book be any different?
Type (don't copy and paste) the following code in JS Bin:
function sayHello(what) {
return "Hello " + what;
}
console.log(sayHello("world"));

Your screen should look something as follows:

An overview of JavaScript

In a nutshell, JavaScript is a prototype-based scripting language with dynamic

typing and first-class function support. JavaScript borrows most of its syntax from
Java, but is also influenced by Awk, Perl, and Python. JavaScript is case-sensitive
and white space-agnostic.

Comments

JavaScript allows single line or multiple line comments. The syntax is similar to
C or Java:
// a one line comment
/* this is a longer,
multi-line comment
*/
/* You can't /* nest comments */ SyntaxError */

[8]


×