(Ebook) Learning JavaScript Data Structures and Algorithms: Write complex and powerful JavaScript code using the latest ECMAScript, 3rd Edition by Loiane Groner ISBN B077NB5H6Y - Download the ebook today and experience the full content
(Ebook) Learning JavaScript Data Structures and Algorithms: Write complex and powerful JavaScript code using the latest ECMAScript, 3rd Edition by Loiane Groner ISBN B077NB5H6Y - Download the ebook today and experience the full content
com
https://ebooknice.com/product/learning-javascript-data-
structures-and-algorithms-write-complex-and-powerful-
javascript-code-using-the-latest-ecmascript-3rd-
edition-42371476
OR CLICK BUTTON
DOWLOAD EBOOK
(Ebook) Learning JavaScript Data Structures and Algorithms by Loiane Groner ISBN
9781785285493, 1785285491
https://ebooknice.com/product/learning-javascript-data-structures-and-
algorithms-5847376
ebooknice.com
https://ebooknice.com/product/estruturas-de-dados-e-algoritmos-com-
javascript-37190150
ebooknice.com
https://ebooknice.com/product/javascript-regular-expressions-55893704
ebooknice.com
(Ebook) Data Structures and Algorithms with JavaScript by Michael McMillan ISBN
9781449364939, 1449364934
https://ebooknice.com/product/data-structures-and-algorithms-with-
javascript-37208884
ebooknice.com
(Ebook) Beginning Functional JavaScript. Functional Programming with JavaScript
using EcmaScript 6 by Anto Aravinth ISBN 9781484226568, 1484226569
https://ebooknice.com/product/beginning-functional-javascript-functional-
programming-with-javascript-using-ecmascript-6-5755216
ebooknice.com
https://ebooknice.com/product/beginning-functional-javascript-functional-
programming-with-javascript-using-ecmascript-6-22627242
ebooknice.com
https://ebooknice.com/product/javascript-data-structures-and-algorithms-an-
introduction-to-understanding-and-implementing-core-data-structure-and-
algorithm-fundamentals-52953836
ebooknice.com
https://ebooknice.com/product/learning-behavior-driven-development-with-
javascript-create-powerful-yet-simple-to-code-bdd-test-suites-in-javascript-
using-the-most-popular-tools-in-the-community-50195346
ebooknice.com
https://ebooknice.com/product/javascript-learning-javascript-data-structures-
and-algorithms-2nd-edition-10609092
ebooknice.com
Learning JavaScript Data Structures and Algorithms
Third Edition
Loiane Groner
BIRMINGHAM - MUMBAI
Learning JavaScript Data
Structures and Algorithms
Third Edition
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.
ISBN 978-1-78862-387-2
www.packtpub.com
To my parents, for their love and support and for guiding me throughout all these years.
To my husband, for his support and for being my loving partner throughout our life journey.
– Loiane Groner
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
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
Learning JavaScript Data Structures and Algorithms  Third Edition
Dedication
Packt Upsell
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
Get in touch
Reviews
1. JavaScript – A Quick Overview
JavaScript data structure and algorithms
Setting up the environment
The minimum setup to work with JavaScript
Using web servers
Node.js http-server
JavaScript basics
Variables
Scope variable
Operators
Truthy and falsy
Functions of the equals operators (== and ===)
Control structures
Conditional statements
Loops
Functions
Object-oriented programming in JavaScript
Debugging and tools
Debugging with VSCode
Summary
2. ECMAScript and TypeScript Overview
ECMAScript or JavaScript?
ES6, ES2015, ES7, ES2016, ES8, ES2017, and ES.Next
The compatibility table
Using Babel.js
ECMAScript 2015+ functionalities
let and const instead of var
Variables scope with let and const
Template literals
Arrow functions
Default parameter values for functions
Declaring the spread and rest operators
Enhanced object properties
Object-oriented programming with classes
Inheritance
Working with getters and setters
Exponentiation operator
Modules
Running ES2015 modules in the browser and with Node.js
Using native ES2015 imports in Node.js
Running ES2015 modules in the browser
ES2015+ backward compatibility
Introducing TypeScript
Type inference
Interfaces
Generics
Other TypeScript functionalities
TypeScript compile-time checking in JavaScript files
Summary
3. Arrays
Why should we use arrays?
Creating and initializing arrays
Accessing elements and iterating an array
Adding elements
Inserting an element at the end of the array
Using the push method
Inserting an element in the first position
Using the unshift method
Removing elements
Removing an element from the end of the array
Removing an element from the first position
Using the shift method
Adding and removing elements from a specific position
Two-dimensional and multi-dimensional arrays
Iterating the elements of two-dimensional arrays
Multi-dimensional arrays
References for JavaScript array methods
Joining multiple arrays
Iterator functions
Iterating using the every method
Iterating using the some method
Iterating using forEach
Using map and filter
Using the reduce method
ECMAScript 6 and new array functionalities
Iterating using the for...of loop
Using the @@iterator object
Array entries, keys, and values
Using the from method
Using the Array.of method
Using the fill method
Using the copyWithin method
Sorting elements
Custom sorting
Sorting strings
Searching
ECMAScript 2015 - the find and findIndex methods
ECMAScript 2016 - using the includes method
Outputting the array into a string
The TypedArray class
Arrays in TypeScript
Summary
4. Stacks
Creating a JavaScript data structure and algorithm library
The stack data structure
Creating an array-based Stack class
Pushing elements to the stack
Popping elements from the stack
Peeking the element from the top of the stack
Verifying whether the stack is empty
Clearing the elements of the stack
Using the Stack class
Creating a JavaScript object-based Stack class
Pushing elements to the stack
Verifying whether the stack is empty and its size
Popping elements from the stack
Peeking the top of the stack and clearing it
Creating the toString method
Protecting the internal elements of the data structure
The underscore naming convention
ES2015 classes with scoped symbols
ES2015 classes with WeakMap
ECMAScript class field proposal
Solving problems using stacks
Converting decimal numbers to binary
The base converter algorithm
Summary
5. Queues and Deques
The queue data structure
Creating the Queue class
Enqueuing elements to the queue
Dequeuing elements from the queue
Peeking the element from the front of the queue
Verifying whether the queue is empty and its size
Clearing the queue
Creating the toString method
Using the Queue class
The deque data structure
Creating the Deque class
Adding elements to the front of the deque
Using the Deque class
Solving problems using queues and deques
The circular queue – Hot Potato
Palindrome checker
JavaScript task queues
Summary
6. Linked Lists
The linked list data structure
Creating the LinkedList class
Pushing elements to the end of the linked list
Removing elements from the linked list from a specific positio
n
Looping through the list until we get to the desired position
Refactoring the remove method
Inserting an element at any position
The indexOf method: returning the position of an element
Removing an element from the linked list
The isEmpty, size, and getHead methods
The toString method
Doubly linked lists
Inserting a new element at any position
Removing elements from any position
Circular linked lists
Inserting a new element at any position
Removing elements from any position
Sorted linked lists
Inserting elements in order
Creating the StackLinkedList class
Summary
7. Sets
Structuring a dataset
Creating a Set class
The has(element) method
The add method
The delete and clear methods
The size method
The values method
Using the Set class
Set operations
Set union
Set intersection
Improving the intersection method
Set difference
Subset
ECMAScript 2015 – the Set class
ES2015 Set class operations
Simulating the union operation
Simulating the intersection operation
Simulating the difference operation
Using the spread operator
Multisets or bags
Summary
8. Dictionaries and Hashes
The dictionary data structure
Creating the Dictionary class
Verifying whether a key exists in the dictionary
Setting a key and value in the dictionary and the ValuePa
ir class
Removing a value from the dictionary
Retrieving a value from the dictionary
The keys, values, and valuePairs methods
Iterating each ValuePair of the dictionary with forEach
The clear, size, isEmpty, and toString methods
Using the Dictionary class
The hash table
Creating a HashTable class
Creating a hash function
Putting a key and a value in the hash table
Retrieving a value from the hash table
Removing a value from the hash table
Using the HashTable class
Hash table versus hash set
Handling collisions between hash tables
Separate chaining
The put method
The get method
The remove method
Linear probing
The put method
The get method
The remove method
Creating better hash functions
The ES2015 Map class
The ES2015 WeakMap and WeakSet classes
Summary
9. Recursion
Understanding recursion
Calculating the factorial of a number
Iterative factorial
Recursive factorial
The call stack
JavaScript limitation on the call stack size
The Fibonacci sequence
Iterative Fibonacci
Recursive Fibonacci
Fibonacci with memoization
Why use recursion? Is it faster?
Summary
10. Trees
The tree data structure
Tree terminology
The binary and binary search trees
Creating the Node and BinarySearchTree classes
Inserting a key into the BST
Tree traversal
In-order traversal
Pre-order traversal
Post-order traversal
Searching for values in a tree
Searching for minimum and maximum values
Searching for a specific value
Removing a node
Removing a leaf node
Removing a node with a left or right child
Removing a node with two children
Self-balancing trees
Adelson-Velskii and Landi’s tree (AVL tree)
Height of a node and the balancing factor
Balancing operations– AVL rotations
Left-left case: single rotation to the right
Right-right case: single rotation to the left
Left-right case: double rotation to the right
Right-left case – double rotation to the left
Inserting a node in the AVL tree
Removing a node from the AVL tree
Red-Black tree
Inserting a node in the Red-Black tree
Verifying the Red-Black tree properties after insertion
Red-Black tree rotations
Summary
11. Binary Heap and Heap Sort
The binary heap data structure
Creating the MinHeap class
Binary tree array representation
Inserting a value into the heap
The sift up operation
Finding the minimum or maximum value from the heap
Extracting the minimum or maximum value from the heap
The sift down operation (heapify)
Creating the MaxHeap class
The heap sort algorithm
Summary
12. Graphs
Graph terminology
Directed and undirected graphs
Representing a graph
The adjacency matrix
The adjacency list
The incidence matrix
Creating the Graph class
Graph traversals
Breadth-first search (BFS)
Finding the shortest paths using BFS
Further study on the shortest paths algorithms
Depth-first search (DFS)
Exploring the DFS algorithm
Topological sorting using DFS
Shortest path algorithms
Dijkstra's algorithm
The Floyd-Warshall algorithm
Minimum spanning tree (MST)
Prim's algorithm
Kruskal's algorithm
Summary
13. Sorting and Searching Algorithms
Sorting algorithms
The bubble sort
The improved bubble sort
The selection sort
The insertion sort
The merge sort
The quick sort
The partition process
The quick sort in action
The counting sort
The bucket sort
The radix sort
Searching algorithms
The sequential search
The binary search
The interpolation search
Shuffle algorithms
The Fisher-Yates shuffle
Summary
14. Algorithm Designs and Techniques
Divide and conquer
Binary search
Dynamic programming
The minimum coin change problem
The knapsack problem
The longest common subsequence
Matrix chain multiplication
Greedy algorithms
The min-coin change problem
The fractional knapsack problem
Backtracking algorithms
Rat in a Maze
Sudoku Solver
Introduction to functional programming
Functional versus imperative programming
ES2015+ and functional programming
The JavaScript functional toolbox – map, filter, and red
uce
JavaScript functional libraries and data structures
Summary
15. Algorithm Complexity
Big O notation
Understanding big O notation
O(1)
O(n)
O(n2)
Comparing complexities
Data structures
Graphs
Sorting Algorithms
Searching Algorithms
Introduction to the NP-completeness theory
Impossible problems and heuristic algorithms
Having fun with algorithms
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
Preface
JavaScript is one of the most popular programming language
nowadays. It is known as the internet language due the fact that the
browser understands JavaScript natively, without installing any
plugins in it. JavaScript has grown so much that is no longer just a
frontend language; it is also present now on the server (NodeJS),
database (MongoDB), and mobile devices and is also used in
embedded and Internet of Things (IoT) devices.
Happy coding!
Who this book is for
If you are a student of computer science or are at the start of your
technology career and want to explore JavaScript’s optimum ability,
this book is for you. If you are already familiar with programming, but
want to hone your skills on algorithms and data structures, this book
is also for you.
, Arrays, explains how to use the most basic and most used
Chapter 3
data structure, which are the arrays. This chapter demonstrates how
to declare, initialize, add, and remove elements from an array. It also
covers how to use native JavaScript Array methods.
, Binary Heap and Heap Sort, covers the min heap and max
Chapter 11
heap data structures, how to use the heap as a priority queue, and
discusses the famous heap sort algorithm.
To test the code examples provided by this book, you will need a
code editor (such as Atom or Visual Studio Code) so that you can
read the code and also a browser (Chrome, Firefox, or Edge).
tools of the browser so that you can see what is being outputted in
the browser's console.
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.
Once the file is downloaded, please make sure that you unzip or
extract the folder using the latest version of:
The code bundle for the book is also hosted on GitHub at https://githu
b.com/PacktPublishing/Learning-JavaScript-Data-Structures-and-Algorithms-Third-Editi
. In case there's an update to the code, it will be updated on the
on
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.
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.
In this chapter, you will learn the syntax and some necessary basic
functionalities of JavaScript so that we can start developing our own
data structures and algorithms. We will cover:
When you open the DevTools, you will see the Console tab, and you
will be able to write all your JavaScript code in its command-line
area, as demonstrated in the following screenshot (to execute the
source code, you need to press Enter):
Random documents with unrelated
content Scribd suggests to you:
—No se requiere sino probar su identidad y luego hacerle ejecutar,
añadió Cobos.
A una señal de D. Jaime, dos soldados condujeron a D. Melchor,
atado codo con codo.
El hermano de doña Dolores de la Cruz, estaba pálido y
descompuesto y llevaba el traje desgarrado y manchado de sangre y
lodo.
Los oficiales se habían constituido en consejo de guerra bajo la
presidencia del general Cobos.
—¿Cómo se llama V.? preguntó éste al reo.
—D. Melchor de la Cruz, respondió en voz sorda el joven.
—¿Confiesa V. haberse pasado al enemigo junto con los soldados
que estaban a sus órdenes?
D. Melchor no respondió, pero se estremeció de píes a cabeza.
—Al tribunal le cabe el convencimiento de que este hombre es un
traidor, dijo Cobos, ¿qué castigo merece?
—Él de los traidores, respondieron unánimemente los oficiales.
—Que le fusilen, dijo el general Cobos.
El reo fue conducido ante el frente de banderas y puesto de rodillas,
y tras él y a seis pasos diez cabos formaron pelotón. Luego Cobos se
acercó al que iban a ejecutar, y le dijo:
—Cobarde y traidor, eres indigno de la jerarquía a que te habían
elevado; por lo tanto, en nombre de todos nuestros compañeros te
declaro degradado y expulso de entre la gente de honor.
Un soldado arrancó entonces a D. Melchor las insignias de su grado
y con ellas le cruzó el rostro.
A este insulto, el joven lanzó un rugido de tigre, tendió en torno de
sí una mirada despavorida e hizo un movimiento para levantarse.
—¡Fuego! gritó el general Cobos.
Resonó una descarga, el reo dio una horrible voz de agonía y cayó
boca abajo, revolcándose entre terribles convulsiones.
—¡Remátenle! dijo el presidente movido a compasión.
—No, repuso Cobos con aspereza; que muera como un perro;
cuanto más padezca más completa será nuestra venganza.
Miramón hizo un gesto de disgusto y ordenó que tocasen botasillas.
Los fugitivos anudaron la marcha.
Sólo dos hombres habían permanecido cerca del infeliz,
contemplándole como se retorcía a sus pies en medio de los más
atroces padecimientos: el general Cobos y D. Jaime.
El cual se inclinó hasta el moribundo, le levantó la cabeza y
obligándole a fijar en él su vidriosa mirada, le dijo en voz sorda:
—¡Parricida, traidor hacia tu patria y hacia tus hermanos, éstos son
los que hoy se vengan; muere como quien eres y llévese tu alma el
diablo; tu cuerpo, privado de sepultura, será pasto de las fieras!
—¡Misericordia! exclamó el desdichado cayendo de espaldas,
¡misericordia!
Una postrer convulsión sacudió el cuerpo del joven, sus crispadas
facciones cobraron un aspecto horrible, lanzó un rugido y quedó
inmóvil.
D. Jaime le empujó con el pie: estaba muerto.
—¡Uno! murmuró el aventurero subiéndose otra vez a caballo.
—¿Qué dice V.? preguntó Cobos.
—Nada, estaba echando una cuenta, respondió D. Jaime riéndose
con zumba.
XX
CARA A CARA
XXI
EPÍLOGO
EL HACHA
ÍNDICE
TOMO SEGUNDO
I. Complicaciones.
II. La sorpresa.
III.Los prisioneros.
IV. Don Diego.
V. La cena.
VI. Revelación.
VII. El vengador.
VIII. Horas de sol.
IX. Un hombre de bien.
X. Amor.
XI. Sorpresa.
XII. La salida.
XIII. Triunfo.
XIV. El Palo Quemado.
XV. Saldo de cuentas.
XVI. Resolución suprema.
XVII. Jesús Domínguez.
XVIII. Principio del fin.
XIX. Golpe de gracia.
XX. Cara a cara.
XXI. Epílogo. El hacha.
*** END OF THE PROJECT GUTENBERG EBOOK LAS NOCHES
MEJICANAS ***
Updated editions will replace the previous one—the old editions will
be renamed.
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.
ebooknice.com