Functional Programming in Javascript How To Improve Your Javascript Programs Using Functional Techniques First Edition Luis Atencio
Functional Programming in Javascript How To Improve Your Javascript Programs Using Functional Techniques First Edition Luis Atencio
com
https://textbookfull.com/product/neural-data-science-a-primer-with-
matlab-and-python-erik-lee-nylen-and-pascal-wallisch-auth/
textbookfull.com
Causation in Insurance Contract Law 2nd Edition Meixian
Song
https://textbookfull.com/product/causation-in-insurance-contract-
law-2nd-edition-meixian-song-2/
textbookfull.com
https://textbookfull.com/product/concurrency-by-tutorials-second-
edition-multithreading-in-swift-with-gcd-and-operations-tutorial-team/
textbookfull.com
https://textbookfull.com/product/see-no-evil-1st-edition-ivy-fox-fox/
textbookfull.com
https://textbookfull.com/product/enemies-to-lovers-her-city-doctor-
the-journals-of-medical-romance-2-1st-edition-lucy-mcconnell-
mcconnell/
textbookfull.com
https://textbookfull.com/product/clinician-s-guide-to-ptsd-2nd-ed-a-
cognitive-behavioral-approach-2nd-edition-steven-taylor/
textbookfull.com
Global Historical Sociology Julian Go
https://textbookfull.com/product/global-historical-sociology-julian-
go/
textbookfull.com
Functional Programming in JavaScript
Functional
Programming
in JavaScript
LUIS ATENCIO
MANNING
SHELTER ISLAND
For online information and ordering of this and other Manning books, please visit
www.manning.com. The publisher offers discounts on this book when ordered in quantity.
For more information, please contact
Special Sales Department
Manning Publications Co.
20 Baldwin Road
PO Box 761
Shelter Island, NY 11964
Email: orders@manning.com
Many of the designations used by manufacturers and sellers to distinguish their products are
claimed as trademarks. Where those designations appear in the book, and Manning
Publications was aware of a trademark claim, the designations have been printed in initial caps
or all caps.
Recognizing the importance of preserving what has been written, it is Manning’s policy to have
the books we publish printed on acid-free paper, and we exert our best efforts to that end.
Recognizing also our responsibility to conserve the resources of our planet, Manning books
are printed on paper that is at least 15 percent recycled and processed without the use of
elemental chlorine.
ISBN: 9781617292828
Printed in the United States of America
1 2 3 4 5 6 7 8 9 10 – EBM – 21 20 19 18 17 16
To my wonderful wife, Ana.
Thank you for your unconditional support
and for being the source of passion and inspiration in my life.
brief contents
PART 1 THINK FUNCTIONALLY ..................................................1
1 ■ Becoming functional 3
2 ■ Higher-order JavaScript 23
vii
contents
preface xv
acknowledgments xvii
about this book xix
1 Becoming functional
1.1
3
Can functional programming help? 5
1.2 What is functional programming? 5
Functional programming is declarative 7 Pure functions and
■
ix
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
x CONTENTS
2 Higher-order JavaScript 23
2.1 Why JavaScript? 24
2.2 Functional vs. object-oriented programming 24
Managing the state of JavaScript objects 31 Treating objects ■
of closures 50
2.5 Summary 53
programming 111
4.6 Managing control flow with functional combinators 112
Identity (I-combinator) 112 Tap (K-combinator) 113
■
null-checking 121
5.2 Building a better solution: functors 121
Wrapping unsafe values 122 ■ Functors explained 124
5.3 Functional error handling using monads 127
Monads: from control flow to data flow 128 Error handling with
■
dependencies 164
6.4 Capturing specifications with property-based testing 166
6.5 Measuring effectiveness through code coverage 172
Measuring the effectiveness of testing functional code 173
Measuring the complexity of functional code 177
6.6 Summary 179
xv
xvi PREFACE
xvii
xviii ACKNOWLEDGMENTS
On the technical side, special thanks to Dean Iverson, who served as the book’s
technical editor; Daniel Lamb, who served as the book’s technical proofreader; and
Brian Hanafee, for his thorough and in-depth evaluation of the entire book. They are
the best technical editors I could have hoped for.
Last but not least, I thank my wife for always supporting me, and my family for
pushing me to become better every day and not asking why I didn’t call as often to
check in while I was writing this book. Also, thanks go to my colleagues at work for
purchasing early releases of the chapters. I am grateful to have the pleasure of work-
ing alongside such wonderful people.
about this book
Complexity is a huge beast to tame, and we’ll never get rid of it entirely; it will always
be an aspect of software development. I’ve spent countless hours and immeasurable
brainpower trying to understand what a particular piece of code does. The secret is to
control the complexity so it doesn’t grow in proportion to the size of your code base—
and functional programming can help. We’re writing more JavaScript than ever before.
We’ve gone from building small client-side event-handling routines, to heavy client-
side architectures, to complete isomorphic (server + client) JavaScript applications.
Functional programming isn’t a tool—it’s a way of thinking that can apply equally to
any of these environments.
This book is designed to teach you how to apply functional programming tech-
niques to your code using ECMAScript 6 JavaScript. The material is presented at a
gradual, steady pace and covers both theoretical and practical aspects of functional
programming. I provide additional information for advanced readers, to help you get
deeper into some of the harder concepts.
Roadmap
This book has eight chapters and is divided into three parts that guide you from fun-
damental building blocks to more-advanced and practical applications of functional
programming.
xix
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
xx ABOUT THIS BOOK
Part 3, “Enhancing your functional skills,” discusses the practical benefits of using
functional programming to tackle real-world challenges:
■ Chapter 6 reveals the inherent ease with which functional programs can be unit
tested. In addition, it introduces a rigorous, automated testing mode called
property-based testing.
■ Chapter 7 takes a look at JavaScript’s memory model, which is used to support
the evaluation of functions. This chapter also discusses techniques that help
optimize the execution time of functional JavaScript applications.
■ Chapter 8 introduces some of the main challenges JavaScript developers face
on a day-to-day basis when dealing with event-driven and asynchronous behav-
ior. It discusses how functional programming can provide elegant solutions to
reduce the complexity of existing imperative solutions with a related paradigm
known as reactive programming, implemented using RxJS.
Typographical conventions
The following conventions are used throughout the book:
■ Italic typeface is used to reference important terms.
■ Courier typeface is used to denote code listings, as well as elements and attri-
butes, methods names, classes, functions, and other programming artifacts.
■ Code annotations accompany some of the source code listings, highlighting
important concepts.
xxii ABOUT THIS BOOK
Author Online
Purchase of Functional Programming in JavaScript includes free access to a private web
forum run by Manning Publications where you can make comments about the book,
ask technical questions, and receive help from the author and from other users. To
access the forum and subscribe to it, point your web browser to https://www.manning
.com/books/functional-programming-in-javascript. This page provides information
on how to get on the forum once you are registered, what kind of help is available,
and the rules of conduct on the forum.
Manning’s commitment to our readers is to provide a venue where a meaningful
dialog between individual readers and between readers and the author can take place.
It is not a commitment to any specific amount of participation on the part of the
author, whose contribution to Author Online remains voluntary (and unpaid). We
suggest you try asking the author some challenging questions lest his interest stray!
The Author Online forum and the archives of previous discussions will be accessible
from the publisher’s website as long as the book is in print.
Part 1
Think functionally
I t’s highly probable that most of your experience building professional appli-
cations has been with an object-oriented language. You may have heard or read
about functional programming in other books, blogs, forums, and magazine
articles, but you’ve probably never written any functional code. Don’t worry; this
is to be expected. I’ve done most of my development in an object-oriented envi-
ronment as well. Writing functional code isn’t difficult, but learning to think
functionally and letting go of old habits is. The primary goal of part 1 of this
book is to lay the foundation for and prepare your mind to embrace the func-
tional techniques discussed in parts 2 and 3.
Chapter 1 discusses what functional programming is and the mindset you
need to embrace it; it also introduces some of the most important techniques
based on pure functions, immutability, side effects, and referential transparency.
These form the backbone of all functional code and will help you transition into
functional more easily. Also, these will be the guiding principles that set the stage
for many of the design decisions we make in the following chapters.
Chapter 2 provides a first view of JavaScript as a functional language. Because
it’s so ubiquitous and mainstream, it’s an ideal language with which to teach func-
tional programming. If you aren’t a strong JavaScript developer, this chapter will
bring you up to speed with everything you need to know to understand functional
JavaScript, such as higher-order functions, closures, and scoping rules.
Random documents with unrelated
content Scribd suggests to you:
seasonable time than now, being Imported hither Custom Free, when all the
other Linnens of Europe pay considerable Duties.
JOHN CARY.
Updated editions will replace the previous one—the old editions will
be renamed.
1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside the
United States, check the laws of your country in addition to the
terms of this agreement before downloading, copying, displaying,
performing, distributing or creating derivative works based on this
work or any other Project Gutenberg™ work. The Foundation makes
no representations concerning the copyright status of any work in
any country other than the United States.
1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if you
provide access to or distribute copies of a Project Gutenberg™ work
in a format other than “Plain Vanilla ASCII” or other format used in
the official version posted on the official Project Gutenberg™ website
(www.gutenberg.org), you must, at no additional cost, fee or
expense to the user, provide a copy, a means of exporting a copy, or
a means of obtaining a copy upon request, of the work in its original
“Plain Vanilla ASCII” or other form. Any alternate format must
include the full Project Gutenberg™ License as specified in
paragraph 1.E.1.
• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”
• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.
1.F.
1.F.4. Except for the limited right of replacement or refund set forth
in paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO
OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.
Please check the Project Gutenberg web pages for current donation
methods and addresses. Donations are accepted in a number of
other ways including checks, online payments and credit card
donations. To donate, please visit: www.gutenberg.org/donate.
Most people start at our website which has the main PG search
facility: www.gutenberg.org.