Functional Programming in JavaScript 1st Edition by Dan Mantyla ISBN 1784398225 9781784398224 - The ebook in PDF format is available for download
Functional Programming in JavaScript 1st Edition by Dan Mantyla ISBN 1784398225 9781784398224 - The ebook in PDF format is available for download
https://ebookball.com/product/functional-programming-in-c-1st-edition-
by-enrico-buonanno-isbn-9781638354048-1638354049-15788/
https://ebookball.com/product/programming-javascript-applications-1st-
edition-by-eric-elliott-1491950250-9781491950258-20264/
https://ebookball.com/product/javascript-mini-faq-1st-edition-by-
danny-goodman-isbn-11420/
Functional Occlusion in Restorative Dentistry and
Prosthodontics 1st Edition by Iven Klineberg, Steven
Eckert ISBN 072343879X 9780723438793
https://ebookball.com/product/functional-occlusion-in-restorative-
dentistry-and-prosthodontics-1st-edition-by-iven-klineberg-steven-
eckert-isbn-072343879x-9780723438793-5506/
https://ebookball.com/product/javascript-and-node-fundamentals-1st-
edition-by-azat-mardan-isbn-b00hdyhkn6-13414/
https://ebookball.com/product/advanced-javascript-2nd-edition-by-
chuck-easttom-isbn-155622852x-9781556228520-13370/
https://ebookball.com/product/jquery-and-javascript-phrasebook-1st-
edition-by-brad-dayley-isbn-0133410854-9780133410853-12804/
Functional Programming in
JavaScript
Table of Contents
Functional Programming in JavaScript
Credits
About the Author
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers and more
Why Subscribe?
Free Access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. The Powers of JavaScript's Functional Side – a Demonstration
Introduction
The demonstration
The application – an e-commerce website
Imperative methods
Functional programming
Summary
2. Fundamentals of Functional Programming
Functional programming languages
What makes a language functional?
Advantages
Cleaner code
Modularity
Reusability
Reduced coupling
Mathematically correct
Functional programming in a nonfunctional world
Is JavaScript a functional programming language?
Working with functions
Self-invoking functions and closures
Higher-order functions
Pure functions
Anonymous functions
Method chains
Recursion
Divide and conquer
Lazy evaluation
The functional programmer's toolkit
Callbacks
Array.prototype.map()
Array.prototype.filter()
Array.prototype.reduce()
Honorable mentions
Array.prototype.forEach
Array.prototype.concat
Array.prototype.reverse
Array.prototype.sort
Array.prototype.every and Array.prototype.some
Summary
3. Setting Up the Functional Programming Environment
Introduction
Functional libraries for JavaScript
Underscore.js
Fantasy Land
Bilby.js
Lazy.js
Bacon.js
Honorable mentions
Development and production environments
Browsers
Server-side JavaScript
A functional use case in the server-side environment
CLI
Using functional libraries with other JavaScript modules
Functional languages that compile into JavaScript
Summary
4. Implementing Functional Programming Techniques in JavaScript
Partial function application and currying
Function manipulation
Apply, call, and the this keyword
Binding arguments
Function factories
Partial application
Partial application from the left
Partial application from the right
Currying
Function composition
Compose
Sequence – compose in reverse
Compositions versus chains
Programming with compose
Mostly functional programming
Handling events
Functional reactive programming
Reactivity
Putting it all together
Summary
5. Category Theory
Category theory
Category theory in a nutshell
Type safety
Object identities
Functors
Creating functors
Arrays and functors
Function compositions, revisited
Monads
Maybes
Promises
Lenses
jQuery is a monad
Implementing categories
Summary
6. Advanced Topics and Pitfalls in JavaScript
Recursion
Tail recursion
The Tail-call elimination
Trampolining
The Y-combinator
Memoization
Variable scope
Scope resolutions
Global scope
Local scope
Object properties
Closures
Gotchas
Function declarations versus function expressions versus the
function constructor
Function declarations
Function expressions
The function constructor
Unpredictable behavior
Summary
7. Functional and Object-oriented Programming in JavaScript
JavaScript – the multi-paradigm language
JavaScript's object-oriented implementation – using prototypes
Inheritance
JavaScript's prototype chain
Inheritance in JavaScript and the Object.create() method
Mixing functional and object-oriented programming in JavaScript
Functional inheritance
Strategy Pattern
Mixins
Classical mixins
Functional mixins
Summary
A. Common Functions for Functional Programming in JavaScript
B. Glossary of Terms
Index
Functional Programming in
JavaScript
Functional Programming in
JavaScript
Copyright © 2015 Packt Publishing
Every effort has been made in the preparation of this book to ensure
the accuracy of the information presented. However, the information
contained in this book is sold without warranty, either express or
implied. Neither the author 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 book.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK
ISBN 978-1-78439-822-4
www.packtpub.com
Dan Mantyla
Reviewers
Dom Derrien
Joe Dorocak
Peter Ehrlich
Commissioning Editor
Julian Ursell
Acquisition Editor
Owen Roberts
Kirti Patil
Technical Editor
Abhishek R. Kotian
Copy Editors
Aditya Nair
Aarti Saldanha
Vikrant Phadkey
Project Coordinator
Nidhi Joshi
Proofreaders
Stephen Copestake
Maria Gould
Paul Hindle
Indexer
Production Coordinator
Aparna Bhagat
Cover Work
Aparna Bhagat
About the Author
Dan Mantyla works as a web application developer for the
University of Kansas. He enjoys contributing to open source web
frameworks and wrenching on motorcycles. Dan is currently living in
Lawrence, Kansas, USA—the birthplace of Python Django and home
to Linux News Media.
Dan has also clicked the cover image, which was taken outside his
home in Lawrence, Kansas, USA, where the sunflower fields are in
bloom for only one short week in September.
About the Reviewers
Dom Derrien is a full stack web developer who has recently been
defining application environments with a focus on high availability
and scalability. He's been in the development field for more than 15
years and has worked for big and small companies and as an
entrepreneur.
I want to thank my wife, Sophie, and our sons, Erwan and Goulven,
with whom I enjoy a peaceful life in Montréal, Québec, Canada.
Did you know that Packt offers eBook versions of every book
published, with PDF and ePub files available? You can upgrade to the
eBook version at www.PacktPub.com and as a print book customer,
you are entitled to a discount on the eBook copy. Get in touch with
us at <service@packtpub.com> for more details.
https://www2.packtpub.com/books/subscription/packtlib
New terms and important words are shown in bold. Words that
you see on the screen, for example, in menus or dialog boxes,
appear in the text like this: "Clicking the Next button moves you to
the next screen."
Note
Warnings or important notes appear in a box like this.
Tip
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what
you think about this book—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.
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.
Customer support
Now that you are the proud owner of a Packt book, we have a
number of things to help you to get the most from your purchase.
Downloading the example code
You can download the example code files from your account at
http://www.packtpub.com for all the Packt Publishing books you
have purchased. If you purchased this book elsewhere, you can visit
http://www.packtpub.com/support and register to have the files e-
mailed directly to you.
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
books—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 book. If you find any errata, please report them by
visiting http://www.packtpub.com/submit-errata, selecting your
book, 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.
In this book, you will learn everything you need to know about
functional programming with JavaScript: how to empower your
JavaScript web applications with functional programming, how to
unlock JavaScript's hidden powers, and how to write better code that
is both more powerful and—because it is smaller—easier to
maintain, faster to download, and takes less overhead. You will also
learn the core concepts of functional programming, how to apply
them to JavaScript, how to side-step the caveats and issues that
may arise when using JavaScript as a functional language, and how
to mix functional programming with object-oriented programming in
JavaScript.
Tip
Downloading the example code
You can download example code files for all Packt books you have
purchased from your account at http://www.packtpub.com. If you
purchased this book elsewhere, you can visit
http://www.packtpub.com/support and register to have the files e-
mailed directly to you.
As you can see, this code is very basic. What if there were many
more coffee styles than just the three we have here? What if there
were 20? 50? What if, in addition to size, there were organic and
non-organic options. That could increase the lines of code extremely
quickly!
Using this method, we are telling the machine what to print for each
coffee type and for each size. This is fundamentally what is wrong
with imperative code.
Functional programming
While imperative code tells the machine, step-by-step, what it needs
to do to solve the problem, functional programming instead seeks to
describe the problem mathematically so that the machine can do the
rest.
// we've now defined how to get the price and label for each
// coffee type and size combination, now we can just print them
coffees.forEach(function(coffee){
printPrice(coffee.getPrice(),coffee.getLabel());
});
var extraLarge = {
getPrice: function(){return this.basePrice + 10},
getLabel: function(){return this.name + ' extra large'}
};
coffeeTypes.push(Peruvian);
coffeeSizes.push(extraLarge);
Arrays of coffee objects and size objects are "mixed" together,—that
is, their methods and member variables are combined—with a
custom function called plusMixin (see Chapter 7, Functional and
Object-oriented Programming in JavaScript). The coffee type classes
contain the member variables and the sizes contain methods to
calculate the name and price. The "mixing" happens within a map
operation, which applies a pure function to each element in an array
and returns a new function inside a reduce() operation—another
higher-order function similar to the map function, except that all the
elements in the array are combined into one. Finally, the new array
of all possible combinations of types and sizes is iterated through
with the forEach() method The forEach() method is yet another
higher-order function that applies a callback function to each object
in an array. In this example, we provide it as an anonymous function
that instantiates the objects and calls the printPrice() function with
the object's getPrice() and getLabel() methods as arguments.
In this chapter, we will first answer these questions and then cover
the core concepts of functional programming:
Using functions and arrays for control flow
Writing pure functions, anonymous functions, recursive
functions, and more
Passing functions around like objects
Utilizing the map(), filter(), and reduce() functions
Functional programming
languages
Functional programming languages are languages that facilitate the
functional programming paradigm. At the risk of oversimplifying, we
could say that, if a language includes the features required for
functional programming, then it is a functional language—as simple
as that. In most cases, it's the programming style that truly
determines whether a program is functional or not.
What makes a language functional?
Functional programming cannot be performed in C. Functional
programming cannot be performed in Java (without a lot of
cumbersome workarounds for "almost" functional programming).
Those and many more languages simply don't contain the constructs
to support it. They are purely object-oriented and strictly non-
functional languages.
But really, it's a little more involved than that. So what makes a
language functional?
Programming Style Perform step-by-step tasks and Define what the problem is and what data
manage changes in state transformations are needed to achieve the solution
Primary Flow Loops, conditionals, and function Function calls and recursion
Control calls
Primary Structures and class objects Functions as first-class objects and data sets
Manipulation Unit
Characteristic Imperative Functional
The syntax of the language must allow for certain design patterns,
such as an inferred type system, and the ability to use anonymous
functions. Essentially, the language must implement Lambda
calculus. Also, the interpreter's evaluation strategy should be non-
strict and call-by-need (also known as deferred execution), which
allows for immutable data structures and non-strict, lazy evaluation.
Advantages
You could say that the profound enlightenment you experience when
you finally "get it" will make learning functional programming worth
it. An experience such as this will make you a better programmer for
the rest of your life, whether you actually become a full-time
functional programmer or not.
But we're not talking about learning to meditate; we're talking about
learning an extremely useful tool that will make you a better
programmer.
Cleaner code
Functional programs are cleaner, simpler, and smaller. This simplifies
debugging, testing, and maintenance.
Both of these functions take the same input and return the same
output. However, the functional example is much more concise and
clean.
Modularity
Functional programming forces large problems to be broken down
into smaller instances of the same problem to be solved. This means
that the code is more modular. Programs that are modular are
clearly specified, easier to debug, and simpler to maintain. Testing is
easier because each piece of modular code can potentially be
checked for correctness.
Reusability
Functional programs share a variety of common helper functions,
due to the modularity of functional programming. You'll find that
many of these functions can be reused for a variety of different
applications.
Reduced coupling
Coupling is the amount of dependency between modules in a
program. Because the functional programmer works to write first-
class, higher-order, pure functions that are completely independent
of each other with no side effects on global variables, coupling is
Other documents randomly have
different content
I have not remitted bills for the salaries of foreign ministers, because
the resolutions of Congress having varied, and Mr Grand having
informed me that he should pay them, I have left it as an account
unsettled to be arranged by Mr Barclay. And as I cannot doubt that
the attachments will have been taken off, and as I have given Mr
Grand a credit on the commissioners of the loan in Holland for four
hundred thousand livres, and directed Messrs Le Couteulx to pay
over to him a balance in their hands, I have no doubt that he will be
in cash for the purpose. I agree with you that a fund ought to be set
apart for contingencies, and had I continued, and been supported in
my administration, such a fund should certainly have been provided.
I am at the same time an enemy to contingent accounts, and
therefore I should have urged the ascertainment of every allowance
as far as possible, thereby curtailing the account of contingencies.
But after all, it cannot be annihilated. Congress have hitherto made
no determination on this subject. Indeed it is very difficult, and even
almost disreputable for them to make arrangements of expenditure,
while the means of expenditure are so shamefully withheld by their
constituents. These things, however, will mend, at least I hope so.
I have already said that I expected the attachments laid on the
public goods would be discharged. Your letter to the Count de
Vergennes on that subject is perfect, and if that minister did not
immediately obtain a compliance with your request, I presume it
must have been occasioned by some circumstances purely domestic,
which we in this country cannot guess at, for certainly nothing can
be more astonishing than to find a subject countenanced in arresting
the property of a sovereign power in this enlightened age, and in the
country, which of all others has been most eminent for a sacred
regard to the rights of nations.
From your last letters to your friends, I find that your return to this
country is somewhat doubtful; I am therefore disappointed in one of
the greatest pleasures, which I had promised myself. But, Sir, in
whatever country you may be, and whether in public or in private
life, be assured of my warmest and most respectful esteem, and that
my best wishes for your happiness shall be clothed with the utmost
efforts in my power to promote it on every proper occasion.
I am, Sir, with perfect respect, &c.
ROBERT MORRIS.
ADVERTISEMENT.
Philadelphia, October 11th, 1784.
The subscriber having taken measures to provide for the payment of
his various engagements on behalf of the United States, and
particularly for such of his notes as may be in circulation, gives this
public notice to all who may be concerned therein, that although he
be no longer in office, yet those notes will all be duly paid at
maturity; and for such payment he hereby pledges himself
personally to the holders, and therefore requests that if any attempt
should be made to obtain them by any suggestions at less than the
specified value, such attempts may be defeated.
ROBERT MORRIS.
FOOTNOTES:
[1] November 3d. This day, on the invitation of the Minister of
France, I attended at the Romish Church at a Te Deum, sung on
account of the capture of Lord Cornwallis and his army. Soon after
arrived the colors taken by General Washington with that array,
which were brought by Colonel Humphreys to Chester, there met
by Colonel Tilghman, and thence conducted hither by those two
Aid-de-Camps of the General. The city troop of light horse went
out to meet them, and became the standard bearers, and
twentyfour gentlemen, privates in that corps, carried each of
them one of the colors displayed. The American and French flags
preceding the captured trophies, which were conducted down
Market street to the Coffee House, thence down Front to Chestnut
street, and up that street to the State House, where they were
presented to Congress, who were sitting; and many of the
members tell me, that instead of viewing this transaction as a
mere matter of joyful ceremony, which they expected to do, they
instantly felt themselves impressed with ideas of the most solemn
nature. It brought to their minds the distresses our country has
been exposed to, the calamities we have repeatedly suffered, the
perilous situation, which our affairs have almost always been in;
and they could not but recollect the threats of Lord North, that he
would bring America to his feet on unconditional terms of
submission. Diary.
[2] January 7th. This day the National Bank of North America
opens to transact business. This institution I am persuaded will
flourish under the management of honest men and honest
measures. The present directors are such men, and the present
system of measures are founded in principles of justice and
equity. Therefore, I shall most cheerfully assist all in my power, to
establish and support this Bank. And as a beginning, I have this
day issued my warrant on the treasury for two hundred thousand
dollars in part of the shares, which I have subscribed, on behalf of
the public. Diary.
[3] January 26th. In consequence of the information received
from Mr Thomas Paine, of the intentions of some officers to
promote a general application by way of memorial to General
Washington, respecting their pay, I sent for him and had a long
conversation on various matters of a public nature. He observed,
that his services to the public had rather been neglected. I told
him I could wish his pen to be wielded in aid of such measures,
as I might be able to convince him were clearly calculated for the
service of the United States; that I had no views or plans but
what were meant for the public good, and that I should ask no
man's assistance on any other ground; that it was true I had
nothing in my power at present to offer, as a compensation for his
services, but that something might turn up, and that I should
have him in my mind.—Diary.
Transcriber's note:
Variations in spelling, punctuation
and hyphenation have been retained
except in obvious cases of
typographical error.
The cover for the eBook version of
this book was created by the
transcriber and is placed in the
public domain.
Omitted words, shown as blank
spaces in the original, have been
transcribed as dashes (——) in the
following cases:
Page 59: As I am not positively
instructed that this loan has
succeeded, I do not venture to draw
bills on you; but in case you shall be
in cash for the United States, which
I expect will happen, you will pay to
Messrs —— & Co., for account of
John Ross, the sum of two hundred
thousand livres; to Messrs Le
Couteulx & Co., for account of
William Bingham, one hundred
thousand livres, and to John Holker,
for account of John Holker fils, the
sum of one hundred thousand. From
each of these persons you will take
quadruplicate receipts, in the form
following; "Received of ——, banker,
by order of the Superintendent of
the Finances of the United States of
North America, on behalf of —— the
sum of —— being so much paid by
the said States to him, the said ——
for which I have signed four
receipts, all of this tenor and date.
Done in Paris this —— day of ——
178—." You will be pleased, Sir, to
forward to me three of the copies by
different opportunities.
Page 62: in my letter of the —— last
Page 62: the invoice sent in my
letter of the —— last
Page 63: the —— last, because I
feel a conviction
Page 66: 1782 is —— dollars,
payable
Page 258: by the time Mr ——
reaches the Havana
Page 259: that Mr ——'s bills be
protested
Page 397: from a tour —— have
been making
"... the subject of paying all
balances ..."
*** END OF THE PROJECT GUTENBERG EBOOK THE DIPLOMATIC
CORRESPONDENCE OF THE AMERICAN REVOLUTION, VOL. 12 ***
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.
Most people start at our website which has the main PG search
facility: www.gutenberg.org.
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.
ebookball.com