ECMAScript Cookbook - Ross Harrison - E-Book

ECMAScript Cookbook E-Book

Ross Harrison

0,0
31,19 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

ECMAScript Cookbook follows a modular approach with independent recipes covering different feature sets and specifications of ECMAScript to help you become an efficient programmer.

This book starts off with organizing your JavaScript applications as well as delivering those applications to modem and legacy systems. You will get acquainted with features of ECMAScript 8 such as async, SharedArrayBuffers, and Atomic operations that enhance asynchronous and parallel operations. In addition to this, this book will introduce you to SharedArrayBuffers, which allow web workers to share data directly, and Atomic operations, which help coordinate behavior across the threads. You will also work with OOP and Collections, followed by new functions and methods on the built-in Object and Array types that make common operations more manageable and less error-prone. You will then see how to easily build more sophisticated and expressive program structures with classes and inheritance. In the end, we will cover Sets, Maps, and Symbols, which are the new types introduced in ECMAScript 6 to add new behaviors and allow you to create simple and powerful modules.

By the end of the book, you will be able to produce more efficient, expressive, and simpler programs using the new features of ECMAScript.
?

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 263

Veröffentlichungsjahr: 2018

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



ECMAScript Cookbook

 

 

 

 

 

 

 

 

 

 

 

 

 

Over 70 recipes to help you learn the new ECMAScript (ES6/ES8) features and solve common JavaScript problems

 

 

 

 

 

 

 

 

 

 

 

 

Ross Harrison

 

 

 

 

 

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

ECMAScript Cookbook

Copyright © 2018 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: Kunal ChaudhariAcquisition Editor: Reshma RamanContent Development Editor:Gauri PradhanTechnical Editor: Leena PatilCopy Editor: Safis EditingProject Coordinator:Sheejal ShahProofreader: Safis EditingIndexer:Tejal Daruwale SoniGraphics:Jason MonteiroProduction Coordinator:Arvindkumar Gupta

First published: March 2018

Production reference: 1280318

Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.

ISBN 978-1-78862-817-4

www.packtpub.com

To my wife Jocelyn, every day that we are together is a joy. I am truly fortunate to spend my life with you.

To my mother and brothers, thanks for dealing with me when I was young and for shaping who I am now.

To my father, "So dawn goes down today. Nothing gold can stay." I miss you.

– Ross Harrison
mapt.io

Mapt is an online digital library that gives you full access to over 5,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

Mapt is fully searchable

Copy and paste, print, and bookmark content

PacktPub.com

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 [email protected] for more details.

At www.PacktPub.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

Ross Harrison discovered programming while he was an undergraduate at the University of Nebraska-Lincoln. His first programming class was a MATLAB class that was required for mechanical engineering. Despite bombing the class, he decided that it was a lot more fun than looking at CAD. He switched to computer science the next semester and never looked back. He has worked as a software engineer for over 10 years. Most of that time has been spent creating tools for digital publishers.

I would like to thank my colleagues at Condé Nast, and John Paul, for getting me started on this process. I would like to thank all of the great people I've worked with at Condé Nast, Rowan Technology, and 42 (Walrus!). I've been lucky enough to work on some pretty cool projects with some really awesome people. I've learned a lot about software and life. 

About the reviewers

Mehul Mohan was born in New Delhi, India, and is completing his education on the Goa Campus at BITS, Pilani as a CSE undergraduate. He is fascinated by programming and the fact that simple programming instructions can perform the most complex calculations known to humans. He primarily works with the MEAN stack. He is the owner of a YouTube channel called codedamn, where he presents screencasts about various programming languages. He has also received many awards from companies such as Google, Microsoft, and Sony through their responsible disclosure programs. He has also authored Learn ECMAScript - Second Edition, which covers ES8 and earlier versions in depth.

I’d like to thank my family and friends for making everything possible! 

 

 

 

 

Kazuki Muta works at a small start-up called Mobilus Corporation, which provides a real-time communication platform and messaging system called MobiAgent.

As a JavaScript engineer, he develops React.js-based web applications and Node.js-based server-side applications.

I am grateful to Takeharu Oshida, for providing me with the opportunity to join this project, and for giving me a lot of technical advice.

 

 

 

 

Rodrigo Oler is a software engineer with a bachelor's degree in information systems from the University of Franca. He currently works at the a start-up Clubinvest as the lead mobile engineer and principal solutions architect. He also works with several start-ups promoting acceleration in technology products, building robust and high-performance solutions. He has been working with JavaScript since 2012. You can visit him on his website @rodrigooler.tk.

I thank all my family, friends and colleagues for their support and dedication, and for the incredible moments together.

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

Title Page

Copyright and Credits

ECMAScript Cookbook

Dedication

PacktPub.com

Why subscribe?

PacktPub.com

Contributors

About the author

About the reviewers

Packt is searching for authors like you

Preface

Who this book is for

What this book covers

To get the most out of this book

Download the example code files

Conventions used

Sections

Getting ready

How to do it...

How it works...

There's more...

See also

Get in touch

Reviews

Building with Modules

Introduction

Installing and configuring - Chrome

Getting ready

How to do it...

How it works...

There's more...

Installing and configuring - Firefox

Getting ready

How to do it...

How it works...

There's more...

Installing Python, using SimpleHTTPServer to host a local static file server

Getting ready

How to do it...

How it works...

Creating an HTML page that loads an ECMAScript module

Getting ready

How to do it...

How it works...

See also

Exporting/importing multiple modules for external use

Getting ready

How to do it...

How it works...

See also

Renaming imported modules

Getting ready

How to do it...

How it works...

Nesting modules under a single namespace

Getting ready

How to do it...

How it works...

There's more...

Staying Compatible with Legacy Browsers

Introduction

Installing Node.js with NVM – Linux and macOS

Getting ready

How to do it...

How it works...

There's more...

Installing Node.js with NVM: Windows

Getting ready

How to do it...

How it works...

There's more...

Installing and configuring webpack

Getting ready

How to do it...

How it works...

Adding fallback script tags to load client bundles

Getting ready

How to do it...

How it works...

See also

Shimming methods with Babel Polyfill

Getting ready

How to do it...

How it works...

Supporting new language features with Babel

Getting ready

How to do it...

How it works...

There's more...

Using tools to analyze webpack bundles

Getting ready

How to do it...

How it works...

Working with Promises

Introduction

Creating and waiting for Promises

Getting ready

How to do it...

How it works...

Resolving Promise results

Getting ready

How to do it...

How it works...

Rejecting Promise errors

Getting ready

How to do it...

How it works...

See also

Chaining Promises

Getting ready

How to do it...

How it works...

See also

Starting a Promise chain with Promise.resolve

Getting ready

How to do it...

How it works...

Using Promise.all to resolve multiple promises

Getting ready

How to do it...

How it works...

There's more

Handling errors with Promise.catch

Getting ready

How to do it...

How it works...

Simulating finally with the promise API

Getting ready

How to do it...

How it works...

Working with async/await and Functions

Introduction

Creating promises with an async function

Getting ready

How to do it...

How it works...

Awaiting the result of async functions

Getting ready

How to do it...

How it works...

Using async results in a Promise chain

Getting ready

How to do it...

How it works...

There's more...

Awaiting multiple results in a series

Getting ready

How to do it...

How it works...

See also

Awaiting multiple results concurrently

Getting ready

How to do it...

How it works...

Using Promise.all to collect an array of async results

Getting ready

How to do it...

How it works...

There's more...

See also

Handling errors when awaiting an async function

Getting ready

How to do it...

How it works...

Handling errors thrown inside of Promise.all

Getting ready

How to do it...

How it works...

Using finally to ensure an operation is performed

Getting ready

How to do it...

How it works...

Web Workers, Shared Memory, and Atomics

Introduction

Enabling SharedArrayBuffers in Firefox

Getting ready

How to do it...

How it works...

Enabling SharedArrayBuffers in Chrome

Getting ready

How to do it...

How it works...

Performing work on separate threads with Web Workers

Getting ready

How to do it...

How it works...

Sending messages to and from Web Workers

Getting ready

How to do it...

How it works...

Sending data to a Web Worker

Getting ready

How to do it...

How it works...

Stopping workers with terminate

Getting ready

How to do it...

How it works...

Creating SharedArrayBuffer

Getting ready

How to do it...

How it works...

Sending SharedArrayBuffer to a Web Worker

Getting ready

How to do it...

How it works...

Reading SharedArray from multiple Web Workers

Getting ready

How to do it...

How it works...

Using Atomics to coordinate the use of shared memory

Getting ready

How to do it...

How it works...

Using promises to provide a simple interface for a worker

Getting ready

How to do it...

How it works...

Plain Objects

Introduction

Using Object.assign to add properties to an object

Getting ready

How to do it...

How it works...

Using Object.entries to get iterable property-name pairs

Getting ready

How to do it...

How it works...

Using Object.is to compare two values

Getting ready

How to do it...

How it works...

Defining function properties as methods on a plain object

Getting ready

How to do it...

How it works...

Defining read-only props with Object.defineProperty

Getting ready

How to do it...

How it works...

Overriding read-only props with Object.defineProperty

Getting ready

How to do it...

How it works...

Creating a non-enumerable property with Object.defineProperty

Getting ready

How to do it...

How it works...

Creating an object using object structuring

Getting ready

How to do it...

How it works...

Picking values from an object using destructuring

Getting ready

How to do it...

How it works...

Using a spread operator to combine objects

Getting ready

How to do it...

How it works...

Creating Classes

Introduction

Creating a new class

Getting ready

How to do it...

How it works...

Assigning properties with constructor arguments

Getting ready

How to do it...

How it works...

Defining methods on a class

Getting ready

How to do it...

How it works...

Checking instance type with instanceOf

Getting ready

How to do it...

How it works...

Using getters to create read-only properties

Getting ready

How to do it...

How it works...

Using setters to encapsulate values

Getting ready

How to do it...

How it works...

Using static methods to work with all instances

Getting ready

How to do it...

How it works...

Inheritance and Composition

Introduction

Extending a class

Getting ready

How to do it...

How it works...

Assigning additional properties with constructor arguments

Getting ready

How to do it...

How it works...

Overriding parent class instance methods

Getting ready

How to do it...

How it works...

Overriding parent class static methods

Getting ready

How to do it...

How it works...

Calling super methods

Getting ready

How to do it...

How it works...

Using composition rather than inheritance to add behavior

Getting ready

How to do it...

How it works...

Using mix-ins to add behavior

Getting ready

How to do it...

How it works...

Passing a class as an argument

Getting ready

How to do it...

How it works...

Checking class inheritance with Object.getPrototypeOf

Getting ready

How to do it...

How it works...

Using throw to simulate abstract classes

Getting ready

How to do it...

How it works...

Larger Structures with Design Patterns

Introduction

Defining steps with template functions

Getting ready

How to do it...

How it works...

Assembling customized instances with builders

Getting ready

How to do it...

How it works...

Replicating instances with factories

Getting ready

How to do it...

How it works...

Processing a structure with the visitor pattern

Getting ready

How to do it...

How it works...

Using a singleton to manage instances

Getting ready

How to do it...

How it works...

Modifying an existing design pattern to fit different use cases

Getting ready

How to do it...

How it works...

Combining existing design patterns to fit different use cases

Getting ready

How to do it...

How it works...

Working with Arrays

Introduction

Using Array#find and Array#filter to find values in an array

Getting ready

How to do it...

How it works...

Using Array#slice to get a subset of the array

Getting ready

How to do it...

How it works...

Using Array#every and Array#some to test array values

Getting ready

How to do it...

How it works...

Using Array.map to produce values

Getting ready

How to do it...

How it works...

Using Array.reduce to transform data

Getting ready

How to do it...

How it works...

Extracting array members with destructuring

Getting ready

How to do it...

How it works...

Getting the head and tail of array using the rest operator

Getting ready

How to do it...

How it works...

Combining arrays with the spread operator

Getting ready

How to do it...

How it works...

Working with Maps and Symbols

Introduction

Using Symbol to create a local instance

Getting ready

How to do it...

How it works...

Using Symbol.for to create a global instance

Getting ready

How to do it...

How it works...

Using Symbol to simulate enums

Getting ready

How to do it...

How it works...

Setting and deleting entries from Map

Getting ready

How to do it...

How it works...

Creating a Map from the existing data

Getting ready

How to do it...

How it works...

Creating a class that wraps Map to work with specific complex types

Getting ready

How to do it...

How it works...

Setting and deleting entries from WeakMap

Getting ready

How to do it...

How it works...

Creating a WeakMap from existing data  

Getting ready

How to do it...

How it works...

Creating a class that uses WeakMap to work with specific complex types

Getting ready

How to do it...

How it works...

Working with Sets

Introduction

Adding and deleting items from a Set

Getting ready

How to do it...

How it works...

Creating a Set from existing data

Getting ready

How to do it...

How it works...

Adding and deleting items from WeakSet

Getting ready

How to do it...

How it works...

Creating a WeakSet from existing data

Getting ready

How to do it...

How it works...

Finding the union of two sets

Getting ready

How to do it...

How it works...

Finding the intersection of two sets

Getting ready

How to do it...

How it works...

Finding the difference between two sets

Getting ready

How to do it...

How it works...

Creating a class that wraps a Set to work with more complex types

Getting ready

How to do it...

How it works...

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

JavaScript permeates the development landscape like few languages before it. Since the introduction of the Node.js run-time in May of 2009, it has ventured far beyond the browser. It now works with controllers on a Raspberry Pi, as the scripting language for 3D video games that run on desktop computers, running web servers that serve millions of page views a day, and, of course, it is the dominant language for web browsers. It is possible that JavaScript is the most important programming language in the world.

The ECMAScript standard has been around almost as long as JavaScript. However, in the last few years, it has seen a flurry of activity. ES6, published in 2015, created an almost completely new language. Since then, the updates have been more gradual, but still significant. This book covers the standard up to ES8 (released in 2017). We'll discuss how to use some of its new features to organize programs more effectively and write better code.

Who this book is for

This book is intended for a broad array of readers. While this should not be considered an introductory text, anyone who has written a JavaScript program and has run it in a browser will be sufficiently prepared to read this book. JavaScript experts will also find some good food for thought. 

What this book covers

Chapter 1, Building with Modules, covers how to use ECMAScript modules to organize code and how to configure modern browsers to use them. This chapter also covers compatibility with Google's Chrome and Mozilla's Firefox browser, and how to make them work with modules.

Chapter 2, Staying Compatible with Legacy Browsers, covers how to convert code that uses ECMAScript modules into a format that can be used by platforms that don't support them. We use webpack, a common JavaScript compilation tool, to assemble our modules into a single JavaScript file (called a bundle) and load it into our browser when ECMASript modules aren't compatible.

 Chapter 3, Working with Promises, covers how to use the Promise API to organize asynchronous programs. We'll take a look at how to propagate results through promise chains and handle errors. Promises are generally regarded as an improvement over the older callback pattern. This chapter also lays a foundation for the topic covered in the next chapter.

Chapter 4, Working with async/await and Functions, covers how to use the new async and await features. Building on the preceding chapter, we'll take a look at how they can be replaced or used in concert with the Promise API, improving program readability while maintaining compatibility.

Chapter 5, Web Workers, Shared Memory, and Atomics, covers the web APIs that can be used to process data in parallel. This chapter is emblematic for the recent development of JavaScript as a language and web browsers as platforms. Parallel programming is a new domain for JavaScript that brings new possibilities and problems to the language.

Chapter 6, Plain Objects, demonstrates the use of API and syntax options to work with plain objects. We'll look at how to work with objects as a collection and how to define properties with some interesting behaviors.

Chapter 7, Creating Classes, covers the use of ECMAScript class semantics. We'll create new classes with behaviors that are defined on single instances and whole classes. We'll take a look at how to add properties and define methods.

Chapter 8, Inheritance and Composition, builds on our knowledge from the preceding chapter; we'll combine classes into larger structures. We'll also take a look at how to use both composition and inheritance to share behaviors between classes, and we'll discuss the benefits and drawbacks of each.

Chapter 9, Larger Structures with Design Patterns, further expanding on the prior two chapters, looks at some common ways that programs are organized for certain tasks. We'll implement some common design patterns and demonstrate how we can expand and modify them for different uses.

Chapter 10, Working with Arrays, covers the use of the new Array API features. In the past, working with arrays meant a lot of loops and keeping track of indices, or importing bulky libraries to clean repeated code. This chapter will show some new, functionally inspired, methods that make working with these collections much easier.

 Chapter 11, Working with Maps and Symbols, covers how to make use of the  Map and WeakMap classes to create relationships between different kinds of values. In this chapter, we'll look at how to use the APIs of these two classes, how they are different, and how we can control which types go into them.

Chapter 12, Working with Sets, demonstrates the use of the Set and WeakSet classes. These classes are excellent when the order of elements doesn't matter, and we just want to is something exists. We'll see how to use the APIs of these two classes, when to use one over the other, and how we can control what types go into them.

To get the most out of this book

This book assumes that you have some very basic knowledge and resources in order to get the most out of it:

A computer with permission to install programs and configure browsers

A text editor you are comfortable with; there are a lot of options to choose from:

VSCode

Atom

Vim

Emacs

Some basic programming knowledge. If you haven't written a function before, this might not be the best place to start.

Download the example code files

You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

Log in or register at

www.packtpub.com

.

Select the

SUPPORT

tab.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box and follow the onscreen instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR/7-Zip for Windows

Zipeg/iZip/UnRarX for Mac

7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/ECMAScript-Cookbook. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "Next, in the same directory, create a file called hello.js, which exports a function named sayHi, which writes a message to the console."

A block of code is set as follows:

// hello.js export function sayHi () { console.log('Hello, World'); }

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

import rocketName, { launch, COUNT_DOWN_DURATION } from './saturn-v.js';

import falconName, { launch as falconLaunch, COUNT_DOWN_DURATION as falconCount } from './falcon-heavy.js';

Any command-line input or output is written as follows:

cd ~/Desktop/es8-cookbook-workspace

Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Double-click nvm-setup."

Warnings or important notes appear like this.
Tips and tricks appear like this.

Sections

In this book, you will find several headings that appear frequently (Getting ready, How to do it..., How it works..., There's more..., and See also).

To give clear instructions on how to complete a recipe, use these sections as follows:

Getting ready

This section tells you what to expect in the recipe and describes how to set up any software or any preliminary settings required for the recipe.

How to do it...

This section contains the steps required to follow the recipe.

How it works...

This section usually consists of a detailed explanation of what happened in the previous section.

There's more...

This section consists of additional information about the recipe in order to make you more knowledgeable about the recipe.

See also

This section provides helpful links to other useful information for the recipe.

Get in touch

Feedback from our readers is always welcome.

General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packtpub.com.

Building with Modules

 In this chapter, we will cover the following recipes:

Installing and configuring browsers—Chrome and Firefox

Installing Python, using SimpleHTTPServer to host a local static file server

Creating an HTML page that loads an ECMAScript module

Exporting/importing multiple modules for external use

Renaming imported modules

Nesting modules under a single namespace

Introduction

JavaScript is the most famous language that adheres to the ECMAScript standard. This standard was created in the late 1990s in order to guide the development of the language. In the early years, development was slow, with only four major versions reaching production in the first two decades. However, with increased exposure, largely thanks to the popularization of the Node.js run-time, the pace of development has increased dramatically. The years 2015, 2016, and 2017 each saw new releases of the of the standard, with another planned for 2018.

With all these developments, now is an exciting time to be a JavaScript developer. A lot of new ideas are coming in from other languages, and the standard API is expanding to be more helpful. This book focuses on new features and techniques that can be used in the newer versions of JS as well as future versions!

Historically, creating JavaScript programs that span multiple files has been a painful experience. The simplest approach was to include each of the files in separate <script> tags. This also requires developers to position the tags in the correct order.

Various libraries have attempted to improve this situation. RequireJS, Browserfy, and Webpack all attempt to solve the problem of JavaScript dependencies and module loading. Each of these requires some kind of configuration or build step.

The situation has improved in recent years. Browser manufacturers collaborate in creating the ECMAScript specification. It is then up to the manufacturers to implement JavaScript interpreters (programs that actually run the JavaScript) that adhere to that specification

New versions of browsers are being released that support native ECMAScript modules. ECMAScript modules provide an elegant method for including dependencies. Best of all, unlike the previous methods, modules don't require any build step or configuration.

The recipes in this chapter focus on installing and configuring the Chrome and Firefox