Functional Programming in JavaScript How to improve your JavaScript programs using functional techniques First Edition Luis Atencio download
Functional Programming in JavaScript How to improve your JavaScript programs using functional techniques First Edition Luis Atencio download
https://textbookfull.com/product/functional-programming-in-
javascript-how-to-improve-your-javascript-programs-using-
functional-techniques-1-edition-edition-luis-atencio/
https://textbookfull.com/product/beginning-functional-javascript-
functional-programming-with-javascript-using-ecmascript-6-1st-
edition-anto-aravinth/
https://textbookfull.com/product/beginning-functional-javascript-
functional-programming-with-javascript-using-ecmascript-6-1st-
edition-anto-aravinth-2/
https://textbookfull.com/product/the-joy-of-javascript-1st-
edition-luis-atencio/
Beginning Functional JavaScript: Uncover the Concepts
of Functional Programming with EcmaScript 8 2nd Edition
Srikanth Machiraju
https://textbookfull.com/product/beginning-functional-javascript-
uncover-the-concepts-of-functional-programming-with-
ecmascript-8-2nd-edition-srikanth-machiraju/
https://textbookfull.com/product/the-joy-of-javascript-1st-
edition-atencio/
https://textbookfull.com/product/head-first-javascript-
programming-2nd-edition-a-learners-guide-to-modern-javascript-
eric-freeman/
https://textbookfull.com/product/head-first-javascript-
programming-2nd-edition-a-learners-guide-to-modern-javascript-
eric-freeman-2/
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: [email protected]
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
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
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.
Becoming functional
If you’re reading this book, chances are you’re a JavaScript developer with a work-
ing knowledge of object-oriented or structured design, and you’re curious about
functional programming. Perhaps you’ve tried to learn it before and haven’t been
able to apply it successfully at work or on your personal projects. In either case,
your main goal is to advance your development skills and improve the quality of
your code. This book can help you accomplish that.
3
4 CHAPTER 1 Becoming functional
The rapid pace of web platforms, the evolution of browsers, and—most impor-
tant—the demands of end users have all had a profound effect on the way we design
web applications today. Users demand that web applications feel more like a native
desktop or a mobile app with rich and responsive widgets. Naturally, these demands
force JavaScript developers to think more broadly about the solution space and to
adopt adequate programming paradigms and best practices that provide the best pos-
sible solutions.
As developers, we gravitate toward frameworks that help us create extensible and
clean application architectures. Yet the complexity of our codebase still gets out of
control, and we’re challenged to reexamine the basic design principles of our code.
Also, the web of today is radically different than it was years ago for JavaScript develop-
ers, because we can do many things now that weren’t technically feasible before. We
can choose to write large server-side applications with Node.js or push the bulk of the
business logic onto the client, leaving a thin server behind. In either case, we need to
interact with storage technology, spawn asynchronous processes, handle events, and
much more.
Object-oriented design helps solve part of the problem; but because JavaScript is
such a dynamic language with lots of shared state, it isn’t long before we accumulate
enough complexity to make our code unwieldy and hard to maintain. Object-oriented
design certainly moves the needle in the right direction, but we need more. Perhaps
you’ve heard the term reactive programming in recent years. This programming para-
digm facilitates working with data flows and propagation of change. In JavaScript, this
is extremely important when dealing with asynchronous or event-based code. Overall,
what we need is a programming paradigm that encourages us to think carefully about
our data and the functions that interact with it. When thinking about an application’s
design, ask yourself the following questions in terms of these design principles:
■ Extensibility—Do I constantly refactor my code to support additional functionality?
■ Easy to modularize—If I change one file, is another file affected?
■ Reusability—Is there a lot of duplication?
■ Testability—Do I struggle to unit test my functions?
■ Easy to reason about—Is my code unstructured and hard to follow?
If you answer “Yes” or “I don’t know” to any of these questions, then you’ve picked up
the right book as a guide on the path to productivity. Functional programming (FP) is
the programming paradigm you need. Although it’s based on simple concepts, FP
requires a shift in the way you think about problems. FP isn’t a new tool or an API, but
a different approach to problem solving that will become intuitive once you under-
stand the basic principles.
In this chapter, I define what functional programming is and tell you how and why
it’s useful and important. I introduce the core principles of immutability and pure func-
tions and talk about FP techniques and how those techniques affect your approach to
designing programs. These techniques allow you to easily pick up reactive programming
What is functional programming? 5
and use it to solve complex JavaScript tasks. But before we can get into all this, you
need to learn why thinking functionally is important and how it can help you tackle
the complexities of JavaScript programs.
and reduce mutation of state in your application. I know this sounds like a mouthful, but
I’ll visit each of these terms further and build on them throughout the book.
Normally, FP books start with computing Fibonacci numbers, but I’d rather start
with a simple JavaScript program that displays text on an HTML page. What better text
to print than the good ol’ “Hello World”:
This program is simple, but because everything is hardcoded, you can’t use it to dis-
play messages dynamically. Say you wanted to change the formatting, the content, or
perhaps the target element; you’d need to rewrite this entire expression. Maybe you
decide to wrap this code with a function and make the change points parameters, so
you can write it once and use it with any configuration:
function printMessage(elementId, format, message) {
document.querySelector(`#${elementId}`).innerHTML =
`<${format}>${message}</${format}>`;
}
An improvement, indeed, but still not a completely reusable piece of code. Suppose
you want to write to a file instead of an HTML page. You need to take the simple
thought process of creating parameterized functions to a different level, where param-
eters aren’t just scalar values but can also be functions themselves that provide addi-
tional functionality. Functional programming is a bit like using functions on steroids,
because your sole objective is to evaluate and combine lots of functions with others to
achieve greater behavior. I’ll fast-forward a bit and show you a sneak peek at this same
program using a functional approach.
printMessage('Hello World');
Without a doubt, this looks radically different than the original. For starters, h1 isn’t a
scalar anymore; it’s a function just like addToDom and echo. Visually, it feels as though
you’re creating a function from smaller functions.
There’s a reason for this madness. Listing 1.1 captures the process of decomposing
a program into smaller pieces that are more reusable, more reliable, and easier to
Random documents with unrelated
content Scribd suggests to you:
The Project Gutenberg eBook of The Diary of a
Hunter from the Punjab to the Karakorum
Mountains
This ebook is for the use of anyone anywhere in the United States
and most other parts of the world at no cost and with almost no
restrictions whatsoever. You may copy it, give it away or re-use it
under the terms of the Project Gutenberg License included with this
ebook or online at www.gutenberg.org. If you are not located in the
United States, you will have to check the laws of the country where
you are located before using this eBook.
Language: English
DIARY OF A HUNTER.
THE
DIARY OF A HUNTER
FROM
THE PUNJAB
TO THE
KARAKORUM MOUNTAINS.
LONDON:
LONGMAN, GREEN, LONGMAN, AND ROBERTS;
NORWICH:
HENRY W. STACY, HAYMARKET.
M.DCCC.LXIII.
NORWICH:
PRINTED BY HENRY W. STACY,
HAYMARKET.
PREFACE.
It is hoped that the circumstances under which this volume appears
may be considered such as to excuse its imperfections. It is—with
some omissions and completions of sentences but with hardly a
verbal alteration—the copy of a journal, not written with a view to
publication but simply as a private record, kept up from time to time
as opportunity offered in the midst of the scenes which it describes.
The hand that wrote it is now in the grave. And it is solely in
compliance with the wishes of many relatives and friends who were
anxious to obtain such a memorial of one whom they loved, that it is
now committed to the press by a brother.
CONTENTS.
PAGE.
CHAPTER I. Preparations and Equipments 1
II. To Sirinuggur 7
III. Sirinuggur—to the Wurdwan 28
IV. Shikar in the Wurdwan 48
V. Ditto 67
VI. Ditto 89
VII. Sooroo Pass to Ladâk 109
VIII. Ladâk 135
IX. Leh 157
X. To the Shayak 176
XI. To the Karakorum 196
XII. Sugheit 225
XIII. The Yâk 249
XIV. The Return 264
XV. Leh and Ladâk 285
XVI. The Bara Sing 302
XVII. Cashmere 324
Browne. Lith. Norwich.
CHAPTER I.
PREPARATIONS AND EQUIPMENTS.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
textbookfull.com