ebook img

Mastering JavaScript Functional Programming PDF

457 Pages·2020·6.616 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Mastering JavaScript Functional Programming

Mastering JavaScript Functional Programming Second Edition Write clean, robust, and maintainable web and server code using functional JavaScript Federico Kereki BIRMINGHAM - MUMBAI Mastering JavaScript Functional Programming Second Edition Copyright © 2020 Packt Publishing All rights reserved. No part of this book 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 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 or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. Commissioning Editor: Wilson D'souza Acquisition Editor: Shweta Bairoliya Content Development Editor: Aamir Ahmed Senior Editor: Hayden Edwards Technical Editor: Jane Dsouza Copy Editor: Safis Editing Project Coordinator: Manthan Patel Proofreader: Safis Editing Indexer: Manju Arasan Production Designer: Joshua Misquitta First published: November 2017 Second edition: January 2020 Production reference: 1240120 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-83921-306-9 www.packt.com Writing a book involves many people, and even if I cannot mention and name all of them, there are some who really deserve to be highlighted. At Packt Publishing, I want to thank Larissa Pinto, Senior Acquisition Editor, for proposing the theme for this book and helping me get started with it. Thanks must also go to Mohammed Yusuf Imaratwale, Content Development Editor, and Ralph Rosario, Technical Editor, for their help in giving shape to the book and making it clearer and better structured. I also want to send my appreciation to the reviewers, Gerónimo García Sgritta and Steve Perkins, who went through the initial draft, enhancing it with their comments. There are some other people who deserve extra consideration. This book was written under unusual circumstances, around 10,000 miles away from home! I had gone from Uruguay, where I live, to work on a project in India, and that's where I wrote every single page of the text. This would not have been possible if I hadn't had complete support from my family, who stayed in Montevideo, but who were constantly nearby, thanks to the internet and modern communications. In particular, I must single out my wife, Sylvia Tosar, not only for supporting and aiding me both with the project and the book, but also for dealing with everything, and the rest of the family on her own in Uruguay—this book wouldn't have been possible otherwise, and she is the greatest reason the book could be written! For the second edition Revisiting and expanding a book for a second edition is a challenging, interesting task. I had great support from Packt, and I must now thank Aamir Ahmed, Content Development Editor; Jane D'souza, Technical Editor; and Crystian Bietti and (again, for double merit!) Steve Perkins, reviewers—both of whom helped produce a much better text. – Federico Kereki Packt.com Subscribe to our online digital library for full access to over 7,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website. Why subscribe? Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals Improve your learning with Skill Plans built especially for you Get a free eBook or video every month Fully searchable for easy access to vital information Copy and paste, print, and bookmark content 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.packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details. At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks. Contributors About the author Federico Kereki is an Uruguayan systems engineer, with a master's degree in education, and more than 30 years of experience as a consultant, system developer, university professor, and writer. He is currently a subject matter expert at Globant, where he gets to use a good mixture of development frameworks, programming tools, and operating systems, such as JavaScript, Node.js, React and Redux, SOA, Containers, and PHP, with both Windows and Linux. He has taught several computer science courses at Universidad de la República, Universidad ORT Uruguay, and Universidad de la Empresa. He has also written texts for these courses. He has written several articles—on JavaScript, web development, and open source topics—for magazines such as Linux Journal and LinuxPro Magazine in the United States, Linux+ and Mundo Linux in Europe, and for websites such as Linux.com and IBM Developer Works. He has also written booklets on computer security (Linux in the Time of Malware and SSH: A Modern Lock for Your Server), a book on GWT programming (Essential GWT: Building for the Web with Google Web Toolkit), and another one on JavaScript development (Modern JavaScript Web Development Cookbook). Federico has given talks on functional programming with JavaScript at public conferences (such as JSCONF 2016 and Development Week Santiago 2019) and has used these techniques to develop internet systems for businesses in Uruguay and abroad. His current interests tend toward software quality and software engineering—with agile methodologies topmost—while on the practical side, he works with diverse languages, tools, and frameworks, and open source software (FLOSS) wherever possible! He usually resides, works, and teaches in Uruguay, but this book was fully written while on a project in India, and the revisions for the second edition were finished during a sojourn in Mexico. About the reviewers Steve Perkins is the author of Hibernate Search by Example. He has been working with Java and JavaScript since the late-1990's, with forays into Scala, Groovy, and Go. Steve lives in Atlanta, GA, with his wife and two children, and is currently a software architect at Banyan Hills Technologies, where he works on a platform for IoT device management and analytics. When he is not writing code or spending time with family, Steve plays guitar and loses games at bridge and backgammon. You can visit his technical blog at steveperkins.com, and follow him on Twitter at @stevedperkins. Cristian "Pusher" Bietti is an entrepreneur who is proactive and has a creative attitude to facing challenges in new technologies, with a great hunger to learn more! A senior developer with more than 18 years of experience in software development and software design and trained in a wide variety of technologies, he has participated in big banking projects and small applications for mobile and social networks, including video games. He has focused on frontend and user experience (UI/UX). He is a subject matter expert at Globant, and he works in the Fintech industry as a technical leader and developer because he loves coding. Packt is searching for authors like you If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea. Table of Contents Preface 1 Technical Requirements 7 Chapter 1: Becoming Functional - Several Questions 8 What is functional programming? 8 Theory versus practice 9 A different way of thinking 10 What FP is not 10 Why use FP? 11 What we need 11 What we get 12 Not all is gold 13 Is JavaScript functional? 13 JavaScript as a tool 14 Going functional with JavaScript 15 Key features of JavaScript 16 Functions as first-class objects 16 Recursion 17 Closures 18 Arrow functions 19 Spread 20 How do we work with JavaScript? 22 Using transpilers 23 Working online 25 Testing 26 Summary 27 Questions 27 Chapter 2: Thinking Functionally - A First Example 29 Our problem – doing something only once 29 Solution 1 – hoping for the best! 30 Solution 2 – using a global flag 31 Solution 3 – removing the handler 32 Solution 4 – changing the handler 33 Solution 5 – disabling the button 33 Solution 6 – redefining the handler 34 Solution 7 – using a local flag 34 A functional solution to our problem 35 A higher-order solution 36 Testing the solution manually 37 Table of Contents Testing the solution automatically 39 Producing an even better solution 41 Summary 42 Questions 43 Chapter 3: Starting Out with Functions - A Core Concept 44 All about functions 44 Of lambdas and functions 45 Arrow functions – the modern way 48 Returning values 49 Handling the this value 49 Working with arguments 51 One argument or many? 53 Functions as objects 54 A React-Redux reducer 55 An unnecessary mistake 57 Working with methods 58 Using functions in FP ways 59 Injection – sorting it out 59 Callbacks, promises, and continuations 62 Continuation passing style 62 Polyfills 64 Detecting Ajax 64 Adding missing functions 66 Stubbing 67 Immediate invocation 68 Summary 71 Questions 71 Chapter 4: Behaving Properly - Pure Functions 73 Pure functions 73 Referential transparency 74 Side effects 76 Usual side effects 76 Global state 77 Inner state 78 Argument mutation 80 Troublesome functions 81 Advantages of pure functions 83 Order of execution 83 Memoization 84 Self-documentation 88 Testing 88 Impure functions 89 Avoiding impure functions 89 Avoiding the usage of state 89 Injecting impure functions 91 Is your function pure? 93 [ ii ] Table of Contents Testing – pure versus impure 94 Testing pure functions 95 Testing purified functions 96 Testing impure functions 99 Summary 102 Questions 102 Chapter 5: Programming Declaratively - A Better Style 104 Transformations 105 Reducing an array to a value 105 Summing an array 107 Calculating an average 108 Calculating several values at once 110 Folding left and right 111 Applying an operation – map 113 Extracting data from objects 115 Parsing numbers tacitly 116 Working with ranges 117 Emulating map() with reduce() 119 Dealing with arrays of arrays 120 Flattening an array 120 Mapping and flattening – flatMap() 123 Emulating flat() and flatMap() 125 More general looping 127 Logical higher-order functions 129 Filtering an array 130 A reduce() example 131 Emulating filter() with reduce() 132 Searching an array 133 A special search case 134 Emulating find() and findIndex() with reduce() 134 Higher-level predicates – some, every 135 Checking negatives – none 136 Working with async functions 137 Some strange behaviors 138 Async-ready looping 140 Looping over async calls 140 Mapping async calls 141 Filtering with async calls 142 Reducing async calls 143 Summary 144 Questions 144 Chapter 6: Producing Functions - Higher-Order Functions 147 Wrapping functions – keeping behavior 148 Logging 149 Logging in a functional way 149 Taking exceptions into account 151 [ iii ]

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.