Functional Programming in JavaScript How to improve your JavaScript programs using functional techniques 1st Edition Luis Atencio download
Functional Programming in JavaScript How to improve your JavaScript programs using functional techniques 1st Edition Luis Atencio download
https://ebookmeta.com/product/functional-programming-in-
javascript-how-to-improve-your-javascript-programs-using-
functional-techniques-1st-edition-luis-atencio/
https://ebookmeta.com/product/mastering-javascript-functional-
programming-1st-edition-federico-kereki/
https://ebookmeta.com/product/functional-javascript-1st-edition-
michael-fogus/
https://ebookmeta.com/product/neuroscience-for-learning-and-
development-how-to-apply-neuroscience-and-psychology-for-
improved-learning-and-training-3rd-edition-stella-collins/
ALU 101 TEXTBOOK BASIC LIFE INSURANCE UNDERWRITING
Academy Of Life Underwriting
https://ebookmeta.com/product/alu-101-textbook-basic-life-
insurance-underwriting-academy-of-life-underwriting/
https://ebookmeta.com/product/the-oxford-handbook-of-nigerian-
politics-a-carl-levan/
https://ebookmeta.com/product/bedside-manner-a-small-town-older-
man-younger-woman-instalove-medical-romance-may-december-romance-
series-1st-edition-violet-rae/
https://ebookmeta.com/product/these-vile-secrets-enclave-1-1st-
edition-ce-ricci-ricci-ce/
https://ebookmeta.com/product/the-princeton-field-guide-to-
dinosaurs-second-edition-gregory-s-paul/
Mr. Park Lane (Mister #4) 1st Edition Louise Bay
https://ebookmeta.com/product/mr-park-lane-mister-4-1st-edition-
louise-bay/
www.ebook3000.com
Functional Programming in JavaScript
www.ebook3000.com
www.ebook3000.com
Functional
Programming
in JavaScript
LUIS ATENCIO
MANNING
SHELTER ISLAND
www.ebook3000.com
For online information and ordering of this and other Manning books,
please visit
20 Baldwin Road
PO Box 761
Email: [email protected]
©2016 by Manning Publications Co. All rights reserved.
20 Baldwin Road
PO Box 761
ISBN: 9781617292828
1 2 3 4 5 6 7 8 9 10 – EBM – 21 20 19 18 17 16
www.ebook3000.com
www.ebook3000.com
www.ebook3000.com
brief contents
PART 1
Becoming functional
3
Higher-order JavaScript
23
PART 2
GET FUNCTIONAL........................................................55
57
84
117
PART 3
ENHANCING YOUR FUNCTIONAL SKILLS...................... 151
153
Functional optimizations
180
205
vii
www.ebook3000.com
www.ebook3000.com
contents
preface
xv
acknowledgments
xvii
xix
1 Becoming functional 3
1.1
1.2
substitutability
15
1.3
16
18 ■ Reacting to the
19
1.4
Summary
22
ix
www.ebook3000.com
CONTENTS
2 Higher-order JavaScript 23
2.1
Why JavaScript?
24
2.2
31 ■ Treating objects
as values
34 ■ Navigating
37
2.3
Functions
38
39 ■ Higher-order functions
40
43 ■ Function methods
44
2.4
45
Problems with the global scope
47 ■ JavaScript’s function
scope
48 ■ A pseudo-block scope
49 ■ Practical applications
of closures
50
2.5
Summary
53
3.1
58
3.2
Method chaining
59
3.3
Function chaining
60
61 ■ Transforming data
with _.map
65
68
3.4
70
71 ■ SQL-like data:
functions as data
75
3.5
77
What is recursion?
79
3.6
Summary
83
4.1
85
86 ■ Arranging functions
in a pipeline
87
CONTENTS
xi
4.2
88
Type-compatible functions
88 ■ Functions and arity:
89
4.3
92
95 ■ Implementing reusable
function templates
97
4.4
98
delayed functions
101
4.5
102
Understanding composition with HTML widgets
102
evaluation
107
programming
111
4.6
112
Identity (I-combinator)
113
Alternation (OR-combinator)
114
4.7
Summary
116
5.1
118
null-checking
121
5.2
121
124
5.3
127
141
5.4
144
5.5
Summary
150
CONTENTS
xii
6.1
Functional programming’s influence on unit tests
154
6.2
155
155
157
158
6.3
159
164
6.4
166
6.5
172
173
177
6.6
Summary
179
7.1
181
recursive code
186
7.2
188
combinator
190
7.3
191
Understanding memoization
intensive functions
memoization
196
Applying memoization to recursive calls
197
7.4
199
201
7.5
Summary
203
CONTENTS
xiii
8.1
206
207
210
8.2
214
asynchronous behavior
221
8.3
224
228
8.4
229
233
8.5
Summary
234
235
index
239
preface
xv
PREFACE
xvi
acknowledgments
xvii
ACKNOWLEDGMENTS
xviii
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
working alongside such wonderful people.
Roadmap
This book has eight chapters and is divided into three parts that
guide you from fundamental building blocks to more-advanced and
practical applications of functional programming.
xix
www.ebook3000.com
xx
xxi
Typographical conventions
xxii
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.
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
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.
Becoming functional
programming
CHAPTER 1
Becoming functional
■
Testability—Do I struggle to unit test my functions?
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 understand the basic principles.
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.
1.1
1.2
CHAPTER 1
Becoming functional
document.querySelector('#msg').innerHTML = '<h1>Hello
World</h1>'; NOTE
document.querySelector(`#${elementId}`).innerHTML =
`<${format}>${message}</${format}>`;
Listing 1.1
Functional printMessage
var printMessage = run(addToDom('msg'), h1, echo);
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
For the time being, you’ll use a magical function, run,1 to invoke a
series of functions sequentially, such as addToDom, h1, and echo. I’ll
explain run in detail later. Behind the scenes, it basically links each
function in a chain-like manner by passing the return value of one as
input to the next. In this case, the string “Hello World” returned from
echo is passed into h1, and the result is finally passed into
addToDom.
Why does the functional solution look this way? I like to think of it as
basically parameterizing your code so that you can easily change it in
a noninvasive manner—
Extending printMessage
Both print the same output, yet they look very different. This is due
to FP’s inherent declarative mode of development. In order to fully
understand functional programming, first you must learn the
fundamental concepts on which it’s based:
Declarative programming
Pure functions
Referential transparency
Immutability
1.2.1
CHAPTER 1
Becoming functional
This is the most common way of writing this code and will most likely
be your first approach to tackling this problem.
Declarative programming, on the other hand, separates program
description from evaluation. It focuses on the use of expressions to
describe what the logic of a program is without necessarily specifying
its control flow or state changes. An example of declarative
programming is found in SQL statements. SQL queries are composed
of statements that describe what the outcome of a query should look
like, abstracting the internal mechanism for data retrieval. In chapter
3, I show an example of using a SQL-like overlay over your functional
code to give meaning to both your application and the data that runs
through it.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(
function(num) {
});
Compared with the previous example, you see that this code frees
you from the responsibility of properly managing a loop counter and
array index access; put simply, the more code you have, the more
places there are for bugs to occur. Also, standard loops aren’t
reusable artifacts unless they’re abstracted with functions. And that’s
precisely what we’ll do. In chapter 3, I demonstrate how to remove
manual loops completely from your code in favor of first-class,
higher-order functions like map, reduce, and filter, which accept
functions as parameters so that your code is more reusable,
extensible, and declarative.
This is what I did with the magical run function in listings 1.1 and
1.2.
function(num) {
}
Why remove loops from your code? A loop is an imperative control
structure that’s hard to reuse and difficult to plug in to other
operations. In addition, it implies code that’s constantly changing or
mutating in response to new iterations. You’ll learn that functional
programs aim for statelessness and immutability as much as possible.
Stateless code has zero chance of changing or breaking global state.
To achieve this, you’ll use functions that avoid side effects and
changes of state, known as pure functions.
1.2.2
var counter = 0;
function increment() {
Other documents randomly have
different content
Saucy girl! her mind seems only filled with lovers. But she would
have her way, and the whole day passed in this occupation. She
boldly untied each package, and resolutely determined I should tell
her the little history appended to each in my memory. The one I held
in my hand when she entered, was first taken up; and we both shed
tears over the sad story it recalled of friendship, love, and a broken-
heart. It is too sad a tale for me to relate to you now, dear reader,
for I am not in the tearful mood. Some gloomy, “gray” day, as Kate
says, I will again recall it, and see if you will sympathize with the
past as did dear Kate Wilson. I have digressed so much already, that
I will take up one of the smallest packages now, and relate to you
the history of my school-girl friend, Lolah Lalande, as she was called
then. Her name is now more famous; but I will keep that a secret
until I arrive at the end of my story. It was a small packet,
containing only a few French letters, a tress of long, glossy black
hair, and a crayon sketch of a childish figure in Spanish costume, and
in one of the attitudes of a Spanish national dance. It had a
beautiful, girlish face, clear, dark eyes—long, sweeping hair—arched,
delicately formed brows—and rich, full lips. That face has turned the
head of a monarch, it is said—but I will not anticipate.
“Tell me this, dear Miss Enna,” said Kate, as she looked at the
contents of the package. “It could not have been a friendship of long
standing—so little remains of it; therefore you will only have a tiny,
little story for me, and I will not teaze you again until—to-morrow, or
the next gray, rainy day.”
Kate listened with affectionate interest; and I’ll never forgive you,
reader, if you are not as indulgent as Kate. But I will seek your favor
in the words of Spenser:
I only saw her that night. The next day we left Munich, and I
never saw her again. From a gentleman I met afterward in Paris,
and who had known Montes from the time of her first appearance in
public, I learned that extreme poverty had driven her to the stage.
She had not been educated for it as a profession; and the touching
account he gave me of her trials, united with my own knowledge of
Lolah Lalande’s history, convinced me that Lolah Lalande and Lolah
Montes were, as I had imagined, one and the same person.
Soon after their arrival in Paris, Madame Lalande discovered that
her move had been an injudicious one. Success did not attend her as
she expected; the château d’Espagne she had created was never
realized; and she found herself, although in her “home,” the
residence of her childhood, among strangers; old associates were
dead, or had formed new connections. Day by day passed, and the
little capital she had collected in America, and which was to establish
the grand school in Paris for les jeunes demoiselles of the nobility,
gradually melted away; and she at last resolved to bid an eternal
farewell to Paris, and return, though with mortified feelings, to the
school in America she had with such blind willfulness given up. But
just as she had come to this conclusion, and Lolah was gladly
making preparations for their return, sickness, caused by extreme
chagrin and disappointment, attacked chère tante. This sickness was
lingering, and at last, bitter, actual poverty stared them in the face.
“What am I to do?” exclaimed poor Lolah, one day, as she turned
from the apothecary’s door, to whom she had just paid her last coin
for medicine for chère tante. Gay equipages dashed past her; and
the busy, bustling crowd moved by, unheeding the misery of that
pale, friendless girl. “God help me,” she murmured, in a thick, hoarse
voice. Sorrow and want had dried up her tears—the real poor
seldom weep. She turned to seek her wretched home, which,
miserable as it was, she knew not how long it might remain to them.
Faint and exhausted with hunger and anxiety, she could scarcely
drag her little feet along the pavé. Regardless of her movements,
she stumbled over a stone; a kind person passing, caught her as she
fell, and upon lifting her eyes to thank him, she recognized Monsieur
Neillet.
“Ah, Mademoiselle Lolah! can this be you?” he exclaimed. “I have
been seeking in vain for Madame Lalande’s residence ever since I
reached Paris;” and then followed a host of questions and
explanations.
The Monsieur had come over to Paris for new dances. A rival had
appeared in the city, where he had so long been the favorite
teacher; and the Americans were raving for new figures. His
gavottes and shawl dances were voted obsolete, and out of date;
and he had been dethroned by the children of his former pupils, to
make way for the new teacher, who came over fresh from Paris with
gallopes and figures of the newest fashion. He could scarcely realize
it until he found his hours unoccupied, his school-list, that had
formerly been filled to overflowing, without a single name; then,
with laudable courage and energy, he resolved to take the little
independence he had collected, return to chère Paris—but not as a
sober Englishman or Scotchman would have done, live quietly on it
for the rest of his days—oh, no! he pined for revenge. What was life
to a Frenchman without a triumph? “Inglorious ease” he scorned.
No! he, too, would learn new dances; he would return to the scene
of his former power, but late discomfiture, and hurl the
presumptuous usurper from his throne. He, too, would flourish in
gallopes and new figures.
The sight of Lolah suffering from poverty and trouble, touched
his warm heart, but gave a new impulse to his thoughts. Monsieur
Neillet was kind and generous; but, like all Frenchmen, ambitious
and enthusiastic. He aided the poor Madame, relieved their
distresses, and asked but one return—to bring his pet pupil out upon
the stage. She consented. Poverty and necessity had humbled
Madame Lalande’s pride—and Lolah became a public danseuse.
Success attended her; and Monsieur Neillet had the satisfaction
of seeing his little Mademoiselle Lolah ride in the grand carriage, and
receive the intoxicating plaudits he had wished for her, when in
Madame Lalande’s school, in America, she had executed à ravir his
favorite gavottes and Spanish waltzes.
I never saw Lolah again. I struggled with my feelings in
exercising this self-denial; but I knew we had both altered, and I felt
that I had rather retain the recollection of our girlish, loving
intercourse undimmed. She was a public danseuse, rich, courted,
and, the world said, free in her morals—I, a plain, unknown woman,
with tastes, associations, and opinions widely differing from hers.
Better to retain the bright recollection of the past, and the uncertain
knowledge of the present, than to risk coldness, or even a realization
of what I feared—that Lolah Montes, the woman, was not the
innocent, pure, guileless Lolah Lalande of school memory. Many may
censure, and call this the cold reasoning of a woman bound down by
conventional prejudices; but how else is a woman to be governed, if
she wishes to secure, not her own happiness, but the happiness of
those around her; and living in a conventional world, she be not
directed and ruled by this same reasoning, which is called cold and
cramping? The gentle graces of charity and indulgence to the
frailties of others, are beautiful, and should be peculiar qualities of
the feminine character; but they may be extended too far, and
instead of giving a helping hand to suffering, oppressed virtue,
encourage evil.
“After all,” said my father, one moonlight evening, as we sat on
the deck of the vessel, “Homeward Bound,” watching the silver flood
of light streaming down upon the billows, and discussing this same
subject, “after all, Enna, she may not be Lolah Lalande, it may only
be a woman’s fancy and imaginings.”
I did not reply; but the recollection of that lovely form, rich, dark,
soul-subduing eyes, and flowing hair, with the delicate brow, and
full, red, laughing lips, came before me strangely blended with the
cold, fierté expression of the tall, beautiful danseuse I looked at in
Munich with tearful eyes. . . .
“I’d have seen her,” said Kate, when I concluded; “I would at
least have satisfied myself.”
“So would I, dear Kate,” I replied, “at your age; but when you are
older, you will argue differently. A recollection of pleasure is better
than a reality of pain.”
Painted by Sir Joshua Reynolds Engraved by H. S. Wagner
The present volume completes this most valuable work, now for
the first time “done” into good English. No better period for the
successful publication of the book could have been selected. The
character and writings of Goethe are now continually made the
subjects of eager praise or fierce invective, even among classes of
readers whose curiosity rarely extends beyond the last novel. Much
both of the praise and blame squandered upon the great German is
directed against a mere man of straw, bearing little resemblance to
the real object. Few of the vehement writers and talkers about
Goethe have taken upon themselves the task of reading and
investigation. His autobiography presents the man and his mind as
they appeared to his own consciousness, and certainly constitutes
one of the most remarkable biographies in literature. It is Goethe’s
portrait drawn by himself, and done with matchless skill. It is worthy
of the most profound study. We should pity the person who could
carefully meditate it without having his knowledge of human nature
increased. That vast mind here discourses of itself with the simplicity
of a child.
Such a volume as this has long been needed in our schools and
academies. Most of the selections from French authors studied by
new beginners, are made from writers of the old school. But within
the last twenty or thirty years there has occurred a kind of idiomatic
revolution in the language, of which the pieces in the present work
are an exemplification. The volume contains selections from Balzac,
Dumas, Victor Hugo, Jules Janin, Lamartine, Sue, Guizot, Michelet,
Thiers, Thierry, Sismondi, Tocqueville, Villemain, and other
celebrated French prose writers of the present day, with translations
of difficult phrases at the bottom of each page. It will be found a
most valuable and interesting French reader.
A beautiful volume bearing this title has been laid upon our table
by the publisher, Mr. Walker, of New York. The work was prepared by
Mr. Benson J. Lossing, and dedicated by him to the youth of our
country, “upon whom will soon devolve the faithful guardianship of
our goodly heritage.” A cursory glance at its contents impresses us
very favorably, as it appears to contain a compendious and well
written account of the original history of the American colonies, the
causes which induced their determination to separate themselves
from a connection with the British government, and the difficulties
and dangers through which this design was carried into effect, and a
free republic established.
The publisher says he “always believed that a book in one
volume, well written, and embracing a faithful chronicle of events
which accomplished the laying of the foundation stone of this great
republic, would be invaluable to the present and all future
generations.” The belief was a just one, and the work before us
seems well calculated to suit the purpose for which it was designed.
Its typographical execution is excellent, and its pages are graced by
seventy-eight beautiful illustrations.
This is a little work which greatly pleases us. It is, as the author
terms it, an attempt to illustrate the first principles of natural
philosophy by the aid of the popular toys and sports of youth, and
he has succeeded admirably in his design. The book may be
commended, with great propriety, to the attention of those who
have the training and culture of the minds of youth, as it conveys a
vast fund of highly important and useful information in a very
attractive and interesting form.
Transcriber’s Notes:
Table of Contents has been added for reader convenience. Archaic
spellings and hyphenation have been retained. Obvious typesetting
and punctuation errors have been corrected without note. Other
errors have been corrected as noted below. For illustrations, some
caption text may be missing or incomplete due to condition of the
originals available for preparation of the eBook.
page 117, ladies; but too poor men ==> ladies; but two poor men
page 119, elité, the young, the ==> élite, the young, the
page 134, with the sail lose, ==> with the sail loose,
page 141, to help to soup. ==> to help himself to soup.
page 151, banished my music-stand, ==> banished from my music-
stand,
page 154, executed a ràvir his favorite ==> executed à ravir his
favorite
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.