100% found this document useful (4 votes)
15 views79 pages

JavaScript Data Structures and Algorithms An Introduction to Understanding and Implementing Core Data Structure and Algorithm Fundamentals 1st Editon by Sammie Bae ISBN 1484239873 9781484239872 pdf download

The document is a comprehensive guide to JavaScript data structures and algorithms, authored by Sammie Bae. It covers fundamental concepts including Big-O notation, JavaScript-specific features, and various data structures like arrays and objects. The book includes exercises and practical examples to enhance understanding and implementation skills.

Uploaded by

ojbixfypct8802
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (4 votes)
15 views79 pages

JavaScript Data Structures and Algorithms An Introduction to Understanding and Implementing Core Data Structure and Algorithm Fundamentals 1st Editon by Sammie Bae ISBN 1484239873 9781484239872 pdf download

The document is a comprehensive guide to JavaScript data structures and algorithms, authored by Sammie Bae. It covers fundamental concepts including Big-O notation, JavaScript-specific features, and various data structures like arrays and objects. The book includes exercises and practical examples to enhance understanding and implementation skills.

Uploaded by

ojbixfypct8802
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 79

JavaScript Data Structures and Algorithms An

Introduction to Understanding and Implementing


Core Data Structure and Algorithm Fundamentals
1st Editon by Sammie Bae ISBN 1484239873
9781484239872 download
https://ebookball.com/product/javascript-data-structures-and-
algorithms-an-introduction-to-understanding-and-implementing-
core-data-structure-and-algorithm-fundamentals-1st-editon-by-
sammie-bae-isbn-1484239873-9781484239872-15798/

Download more ebook instantly today at https://ebookball.com


Get Your Digital Files Instantly: PDF, ePub, MOBI and More
Quick Digital Downloads: PDF, ePub, MOBI and Other Formats

A Practical Introduction to Data Structures And Algorithm Analysis 3rd


Edition by Clifford Shaffer

https://ebookball.com/product/a-practical-introduction-to-data-
structures-and-algorithm-analysis-3rd-edition-by-clifford-
shaffer-15310/

Data Structures and Algorithms Made Easy Data Structure and


Algorithmic Puzzles 5th Edition by Careermonk Publications, Narasimha
Karumanchi ISBN 9788193245279

https://ebookball.com/product/data-structures-and-algorithms-
made-easy-data-structure-and-algorithmic-puzzles-5th-edition-by-
careermonk-publications-narasimha-karumanchi-
isbn-9788193245279-15800/

Data Structures and Algorithms 1st Edition by Alfred Aho ISBN


0201000237 9780201000238

https://ebookball.com/product/data-structures-and-algorithms-1st-
edition-by-alfred-aho-isbn-0201000237-9780201000238-25072/

Data Structures and Algorithm Analysis in JavaTM 3rd edition by Mark


Weiss 9780133465013 0133465012

https://ebookball.com/product/data-structures-and-algorithm-
analysis-in-javatm-3rd-edition-by-mark-
weiss-9780133465013-0133465012-18710/
Data Structures And Algorithm Analysis in C 4th Edition by Mark Weiss
013284737X 9780132847377

https://ebookball.com/product/data-structures-and-algorithm-
analysis-in-c-4th-edition-by-mark-
weiss-013284737x-9780132847377-15292/

Data Structures and Algorithms in Java 1st Edition by Peter Drake ISBN
0131469142 9780131469143

https://ebookball.com/product/data-structures-and-algorithms-in-
java-1st-edition-by-peter-drake-
isbn-0131469142-9780131469143-12422/

Data Structures and Algorithms in C 1st edition by Adam Drozdek ASIN


B002WLXMBY

https://ebookball.com/product/data-structures-and-algorithms-
in-c-1st-edition-by-adam-drozdek-asin-b002wlxmby-25076/

Data Structures and Algorithm Analysis in C++ 3rd edition by Clifford


Shaffer ISBN 048648582X 978-0486485829

https://ebookball.com/product/data-structures-and-algorithm-
analysis-in-c-3rd-edition-by-clifford-shaffer-
isbn-048648582x-978-0486485829-16486/

Data Structures Algorithms and Applications in C++ 1st edition by Adam


Drozdek ISBN 1133608426 9781133608424

https://ebookball.com/product/data-structures-algorithms-and-
applications-in-c-1st-edition-by-adam-drozdek-
isbn-1133608426-9781133608424-17250/
JavaScript Data
Structures and
Algorithms
An Introduction to Understanding and
Implementing Core Data Structure and
Algorithm Fundamentals

Sammie Bae
JavaScript Data Structures
and Algorithms
An Introduction to Understanding
and Implementing Core Data
Structure and Algorithm
Fundamentals

Sammie Bae
JavaScript Data Structures and Algorithms
Sammie Bae
Hamilton, ON, Canada

ISBN-13 (pbk): 978-1-4842-3987-2 ISBN-13 (electronic): 978-1-4842-3988-9


https://doi.org/10.1007/978-1-4842-3988-9
Library of Congress Control Number: 2019930417

Copyright © 2019 by Sammie Bae


This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the
material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation,
broadcasting, reproduction on microfilms or in any other physical way, and transmission or information
storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now
known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with
every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an
editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the
trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not
identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to
proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication,
neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or
omissions that may be made. The publisher makes no warranty, express or implied, with respect to the
material contained herein.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: Louise Corrigan
Development Editor: Chris Nelson
Coordinating Editor: Nancy Chen
Cover designed by eStudioCalamar
Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street,
6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-
sbm.com, or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member
(owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a
Delaware corporation.
For information on translations, please e-mail [email protected], or visit www.apress.com/
rights-permissions.
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and
licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales
web page at www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is available to
readers on GitHub via the book’s product page, located at www.apress.com/9781484239872. For more
detailed information, please visit www.apress.com/source-code.
Printed on acid-free paper
This book is dedicated to Dr. Hamid R. Tizhoosh for inspiring
me in my studies and to my mother, Min Kyoung Seo, for her
kindness and support.
Table of Contents
About the Author �����������������������������������������������������������������������������������������������������xv

About the Technical Reviewer �������������������������������������������������������������������������������xvii

Acknowledgments ��������������������������������������������������������������������������������������������������xix

Introduction ������������������������������������������������������������������������������������������������������������xxi

Chapter 1: Big-O Notation ����������������������������������������������������������������������������������������� 1


Big-O Notation Primer ������������������������������������������������������������������������������������������������������������������� 1
Common Examples ������������������������������������������������������������������������������������������������������������������ 2
Rules of Big-O Notation����������������������������������������������������������������������������������������������������������������� 4
Coefficient Rule: “Get Rid of Constants”���������������������������������������������������������������������������������� 5
Sum Rule: “Add Big-Os Up” ����������������������������������������������������������������������������������������������������� 6
Product Rule: “Multiply Big-Os” ���������������������������������������������������������������������������������������������� 7
Polynomial Rule: “Big-O to the Power of k”����������������������������������������������������������������������������� 8
Summary��������������������������������������������������������������������������������������������������������������������������������������� 8
Exercises ��������������������������������������������������������������������������������������������������������������������������������������� 9
Answers��������������������������������������������������������������������������������������������������������������������������������� 11

Chapter 2: JavaScript: Unique Parts ����������������������������������������������������������������������� 13


JavaScript Scope ������������������������������������������������������������������������������������������������������������������������ 13
Global Declaration: Global Scope������������������������������������������������������������������������������������������� 13
Declaration with var: Functional Scope ��������������������������������������������������������������������������������� 13
Declaration with let: Block Scope ������������������������������������������������������������������������������������������ 15

v
Table of Contents

Equality and Types���������������������������������������������������������������������������������������������������������������������� 16


Variable Types������������������������������������������������������������������������������������������������������������������������ 16
Truthy/Falsey Check�������������������������������������������������������������������������������������������������������������� 17
=== vs ==���������������������������������������������������������������������������������������������������������������������������� 18
Objects���������������������������������������������������������������������������������������������������������������������������������� 18
Summary������������������������������������������������������������������������������������������������������������������������������������ 20

Chapter 3: JavaScript Numbers������������������������������������������������������������������������������ 21


Number System�������������������������������������������������������������������������������������������������������������������������� 21
JavaScript Number Object���������������������������������������������������������������������������������������������������������� 23
Integer Rounding������������������������������������������������������������������������������������������������������������������� 23
Number.EPSILON������������������������������������������������������������������������������������������������������������������� 24
Maximums����������������������������������������������������������������������������������������������������������������������������� 24
Minimums������������������������������������������������������������������������������������������������������������������������������ 25
Size Summary����������������������������������������������������������������������������������������������������������������������� 26
Number Algorithms���������������������������������������������������������������������������������������������������������������� 26
Prime Factorization��������������������������������������������������������������������������������������������������������������� 28
Random Number Generator�������������������������������������������������������������������������������������������������������� 29
Exercises������������������������������������������������������������������������������������������������������������������������������������� 29
Summary������������������������������������������������������������������������������������������������������������������������������������ 34

Chapter 4: JavaScript Strings��������������������������������������������������������������������������������� 35


JavaScript String Primitive��������������������������������������������������������������������������������������������������������� 35
String Access������������������������������������������������������������������������������������������������������������������������� 35
String Comparison����������������������������������������������������������������������������������������������������������������� 36
String Search������������������������������������������������������������������������������������������������������������������������� 36
String Decomposition������������������������������������������������������������������������������������������������������������ 38
String Replace����������������������������������������������������������������������������������������������������������������������� 38
Regular Expressions������������������������������������������������������������������������������������������������������������������� 38
Basic Regex��������������������������������������������������������������������������������������������������������������������������� 39
Commonly Used Regexes������������������������������������������������������������������������������������������������������ 39
Encoding������������������������������������������������������������������������������������������������������������������������������������� 41
Base64 Encoding������������������������������������������������������������������������������������������������������������������� 42

vi
Table of Contents

String Shortening������������������������������������������������������������������������������������������������������������������������ 43
Encryption����������������������������������������������������������������������������������������������������������������������������������� 45
RSA Encryption���������������������������������������������������������������������������������������������������������������������� 46
Summary������������������������������������������������������������������������������������������������������������������������������� 50

Chapter 5: JavaScript Arrays��������������������������������������������������������������������������������� 53


Introducing Arrays����������������������������������������������������������������������������������������������������������������������� 53
Insertion�������������������������������������������������������������������������������������������������������������������������������� 53
Deletion��������������������������������������������������������������������������������������������������������������������������������� 54
Access����������������������������������������������������������������������������������������������������������������������������������� 54
Iteration��������������������������������������������������������������������������������������������������������������������������������������� 54
for (Variables; Condition; Modification)��������������������������������������������������������������������������������� 55
for ( in )���������������������������������������������������������������������������������������������������������������������������������� 56
for ( of )���������������������������������������������������������������������������������������������������������������������������������� 56
forEach( )�������������������������������������������������������������������������������������������������������������������������������� 56
Helper Functions������������������������������������������������������������������������������������������������������������������������� 57
.slice(begin,end)�������������������������������������������������������������������������������������������������������������������� 57
.splice(begin,size,element1,element2…)������������������������������������������������������������������������������ 58
.concat()��������������������������������������������������������������������������������������������������������������������������������� 59
.length Property��������������������������������������������������������������������������������������������������������������������� 59
Spread Operator�������������������������������������������������������������������������������������������������������������������� 60
Exercises������������������������������������������������������������������������������������������������������������������������������������� 60
JavaScript Functional Array Methods����������������������������������������������������������������������������������������� 67
Map��������������������������������������������������������������������������������������������������������������������������������������� 67
Filter�������������������������������������������������������������������������������������������������������������������������������������� 68
Reduce���������������������������������������������������������������������������������������������������������������������������������� 68
Multidimensional Arrays������������������������������������������������������������������������������������������������������������� 68
Exercises������������������������������������������������������������������������������������������������������������������������������������� 71
Summary������������������������������������������������������������������������������������������������������������������������������������ 81

vii
Table of Contents

Chapter 6: JavaScript Objects�������������������������������������������������������������������������������� 83


JavaScript Object Property��������������������������������������������������������������������������������������������������������� 83
Prototypal Inheritance����������������������������������������������������������������������������������������������������������������� 84
Constructor and Variables����������������������������������������������������������������������������������������������������������� 85
Summary������������������������������������������������������������������������������������������������������������������������������������ 86
Exercises������������������������������������������������������������������������������������������������������������������������������������� 87

Chapter 7: JavaScript Memory Management��������������������������������������������������������� 89


Memory Leaks���������������������������������������������������������������������������������������������������������������������������� 89
Reference to an Object���������������������������������������������������������������������������������������������������������� 89
Leaking DOM������������������������������������������������������������������������������������������������������������������������� 90
Global window Object������������������������������������������������������������������������������������������������������������ 91
Limiting Object References��������������������������������������������������������������������������������������������������� 92
The delete Operator��������������������������������������������������������������������������������������������������������������� 92
Summary������������������������������������������������������������������������������������������������������������������������������������ 93
Exercises������������������������������������������������������������������������������������������������������������������������������������� 93

Chapter 8: Recursion���������������������������������������������������������������������������������������������� 99
Introducing Recursion����������������������������������������������������������������������������������������������������������������� 99
Rules of Recursion�������������������������������������������������������������������������������������������������������������������� 100
Base Case���������������������������������������������������������������������������������������������������������������������������� 100
Divide-and-Conquer Method����������������������������������������������������������������������������������������������� 101
Classic Example: Fibonacci Sequence�������������������������������������������������������������������������������� 101
Fibonacci Sequence: Tail Recursion������������������������������������������������������������������������������������ 102
Pascal’s Triangle������������������������������������������������������������������������������������������������������������������ 103
Big-O for Recursion������������������������������������������������������������������������������������������������������������������� 105
Recurrence Relations���������������������������������������������������������������������������������������������������������� 105
Master Theorem������������������������������������������������������������������������������������������������������������������ 106
Recursive Call Stack Memory��������������������������������������������������������������������������������������������������� 107
Summary���������������������������������������������������������������������������������������������������������������������������������� 109
Exercises����������������������������������������������������������������������������������������������������������������������������������� 109

viii
Table of Contents

Chapter 9: Sets����������������������������������������������������������������������������������������������������� 117


Introducing Sets������������������������������������������������������������������������������������������������������������������������ 117
Set Operations�������������������������������������������������������������������������������������������������������������������������� 117
Insertion������������������������������������������������������������������������������������������������������������������������������ 118
Deletion������������������������������������������������������������������������������������������������������������������������������� 118
Contains������������������������������������������������������������������������������������������������������������������������������� 118
Other Utility Functions�������������������������������������������������������������������������������������������������������������� 119
Intersection�������������������������������������������������������������������������������������������������������������������������� 119
isSuperSet��������������������������������������������������������������������������������������������������������������������������� 119
Union����������������������������������������������������������������������������������������������������������������������������������� 120
Difference���������������������������������������������������������������������������������������������������������������������������� 120
Summary���������������������������������������������������������������������������������������������������������������������������������� 121
Exercises����������������������������������������������������������������������������������������������������������������������������������� 122

Chapter 10: Searching and Sorting���������������������������������������������������������������������� 125


Searching���������������������������������������������������������������������������������������������������������������������������������� 125
Linear Search���������������������������������������������������������������������������������������������������������������������� 125
Binary Search���������������������������������������������������������������������������������������������������������������������� 127
Sorting�������������������������������������������������������������������������������������������������������������������������������������� 129
Bubble Sort�������������������������������������������������������������������������������������������������������������������������� 129
Selection Sort���������������������������������������������������������������������������������������������������������������������� 131
Insertion Sort����������������������������������������������������������������������������������������������������������������������� 132
Quicksort����������������������������������������������������������������������������������������������������������������������������� 134
Quickselect�������������������������������������������������������������������������������������������������������������������������� 137
Mergesort���������������������������������������������������������������������������������������������������������������������������� 138
Count Sort���������������������������������������������������������������������������������������������������������������������������� 140
JavaScript’s Built-in Sort����������������������������������������������������������������������������������������������������� 141
Summary���������������������������������������������������������������������������������������������������������������������������������� 142
Exercises����������������������������������������������������������������������������������������������������������������������������������� 143

ix
Table of Contents

Chapter 11: Hash Tables��������������������������������������������������������������������������������������� 151


Introducing Hash Tables������������������������������������������������������������������������������������������������������������ 151
Hashing Techniques������������������������������������������������������������������������������������������������������������������ 152
Prime Number Hashing������������������������������������������������������������������������������������������������������� 152
Probing�������������������������������������������������������������������������������������������������������������������������������� 154
Rehashing/Double-Hashing������������������������������������������������������������������������������������������������� 155
Hash Table Implementation������������������������������������������������������������������������������������������������������� 156
Using Linear Probing����������������������������������������������������������������������������������������������������������� 156
Using Quadratic Probing������������������������������������������������������������������������������������������������������ 158
Using Double-Hashing with Linear Probing������������������������������������������������������������������������� 160
Summary���������������������������������������������������������������������������������������������������������������������������������� 161

Chapter 12: Stacks and Queues���������������������������������������������������������������������������� 163


Stacks��������������������������������������������������������������������������������������������������������������������������������������� 163
Peek������������������������������������������������������������������������������������������������������������������������������������� 165
Insertion������������������������������������������������������������������������������������������������������������������������������ 165
Deletion������������������������������������������������������������������������������������������������������������������������������� 166
Access��������������������������������������������������������������������������������������������������������������������������������� 166
Search��������������������������������������������������������������������������������������������������������������������������������� 167
Queues�������������������������������������������������������������������������������������������������������������������������������������� 167
Peek������������������������������������������������������������������������������������������������������������������������������������� 169
Insertion������������������������������������������������������������������������������������������������������������������������������ 169
Deletion������������������������������������������������������������������������������������������������������������������������������� 169
Access��������������������������������������������������������������������������������������������������������������������������������� 170
Search��������������������������������������������������������������������������������������������������������������������������������� 171
Summary���������������������������������������������������������������������������������������������������������������������������������� 171
Exercises����������������������������������������������������������������������������������������������������������������������������������� 172

Chapter 13: Linked Lists��������������������������������������������������������������������������������������� 179


Singly Linked Lists�������������������������������������������������������������������������������������������������������������������� 179
Insertion������������������������������������������������������������������������������������������������������������������������������ 180
Deletion by Value����������������������������������������������������������������������������������������������������������������� 181

x
Table of Contents

Deletion at the Head������������������������������������������������������������������������������������������������������������ 182


Search��������������������������������������������������������������������������������������������������������������������������������� 183
Doubly Linked Lists������������������������������������������������������������������������������������������������������������������� 184
Insertion at the Head����������������������������������������������������������������������������������������������������������� 185
Insertion at the Tail�������������������������������������������������������������������������������������������������������������� 185
Deletion at the Head������������������������������������������������������������������������������������������������������������ 186
Deletion at the Tail��������������������������������������������������������������������������������������������������������������� 187
Search��������������������������������������������������������������������������������������������������������������������������������� 188
Summary���������������������������������������������������������������������������������������������������������������������������������� 189
Exercises����������������������������������������������������������������������������������������������������������������������������������� 190

Chapter 14: Caching��������������������������������������������������������������������������������������������� 193


Understanding Caching������������������������������������������������������������������������������������������������������������� 193
Least Frequently Used Caching������������������������������������������������������������������������������������������������� 194
Least Recently Used Caching���������������������������������������������������������������������������������������������������� 199
Summary���������������������������������������������������������������������������������������������������������������������������������� 203

Chapter 15: Trees�������������������������������������������������������������������������������������������������� 205


General Tree Structure�������������������������������������������������������������������������������������������������������������� 205
Binary Trees������������������������������������������������������������������������������������������������������������������������������ 206
Tree Traversal���������������������������������������������������������������������������������������������������������������������������� 207
Pre-order Traversal�������������������������������������������������������������������������������������������������������������� 207
In-Order Traversal���������������������������������������������������������������������������������������������������������������� 209
Post-order Traversal������������������������������������������������������������������������������������������������������������ 211
Level-Order Traversal���������������������������������������������������������������������������������������������������������� 212
Tree Traversal Summary������������������������������������������������������������������������������������������������������ 214
Binary Search Trees������������������������������������������������������������������������������������������������������������������ 214
Insertion������������������������������������������������������������������������������������������������������������������������������ 216
Deletion������������������������������������������������������������������������������������������������������������������������������� 218
Search��������������������������������������������������������������������������������������������������������������������������������� 220

xi
Table of Contents

AVL Trees����������������������������������������������������������������������������������������������������������������������������������� 221


Single Rotation�������������������������������������������������������������������������������������������������������������������� 221
Double Rotation������������������������������������������������������������������������������������������������������������������� 225
Balancing the Tree��������������������������������������������������������������������������������������������������������������� 228
Insertion������������������������������������������������������������������������������������������������������������������������������ 229
Putting It All Together: AVL Tree Example����������������������������������������������������������������������������� 231
Summary���������������������������������������������������������������������������������������������������������������������������������� 234
Exercises����������������������������������������������������������������������������������������������������������������������������������� 234

Chapter 16: Heaps������������������������������������������������������������������������������������������������ 245


Understanding Heaps���������������������������������������������������������������������������������������������������������������� 245
Max-Heap���������������������������������������������������������������������������������������������������������������������������� 246
Min-Heap����������������������������������������������������������������������������������������������������������������������������� 247
Binary Heap Array Index Structure�������������������������������������������������������������������������������������������� 248
Percolation: Bubbling Up and Down������������������������������������������������������������������������������������ 250
Implementing Percolation��������������������������������������������������������������������������������������������������� 253
Max-Heap Example������������������������������������������������������������������������������������������������������������� 254
Min-Heap Complete Implementation���������������������������������������������������������������������������������������� 258
Max-Heap Complete Implementation��������������������������������������������������������������������������������������� 259
Heap Sort���������������������������������������������������������������������������������������������������������������������������������� 261
Ascending-Order Sort (Min-Heap)��������������������������������������������������������������������������������������� 261
Descending-Order Sort (Max-Heap)������������������������������������������������������������������������������������ 264
Summary���������������������������������������������������������������������������������������������������������������������������������� 267
Exercises����������������������������������������������������������������������������������������������������������������������������������� 268

Chapter 17: Graphs����������������������������������������������������������������������������������������������� 273


Graph Basics����������������������������������������������������������������������������������������������������������������������������� 273
Undirected Graphs�������������������������������������������������������������������������������������������������������������������� 277
Adding Edges and Vertices�������������������������������������������������������������������������������������������������� 279
Removing Edges and Vertices��������������������������������������������������������������������������������������������� 280
Directed Graphs������������������������������������������������������������������������������������������������������������������������ 282

xii
Table of Contents

Graph Traversal������������������������������������������������������������������������������������������������������������������������� 285


Breadth-First Search����������������������������������������������������������������������������������������������������������� 286
Depth-First Search�������������������������������������������������������������������������������������������������������������� 289
Weighted Graphs and Shortest Path����������������������������������������������������������������������������������������� 293
Graphs with Weighted Edges����������������������������������������������������������������������������������������������� 293
Dijkstra’s Algorithm: Shortest Path�������������������������������������������������������������������������������������� 294
Topological Sort������������������������������������������������������������������������������������������������������������������������ 298
Summary���������������������������������������������������������������������������������������������������������������������������������� 300

Chapter 18: Advanced Strings������������������������������������������������������������������������������ 303


Trie (Prefix Tree)������������������������������������������������������������������������������������������������������������������������ 303
Boyer–Moore String Search������������������������������������������������������������������������������������������������������ 307
Knuth–Morris–Pratt String Search�������������������������������������������������������������������������������������������� 311
Rabin–Karp Search������������������������������������������������������������������������������������������������������������������� 316
The Rabin Fingerprint���������������������������������������������������������������������������������������������������������� 316
Applications in Real Life������������������������������������������������������������������������������������������������������ 319
Summary���������������������������������������������������������������������������������������������������������������������������������� 320

Chapter 19: Dynamic Programming��������������������������������������������������������������������� 321


Motivations for Dynamic Programming������������������������������������������������������������������������������������ 321
Rules of Dynamic Programming����������������������������������������������������������������������������������������������� 323
Overlapping Subproblems��������������������������������������������������������������������������������������������������� 323
Optimal Substructure���������������������������������������������������������������������������������������������������������� 323
Example: Ways to Cover Steps�������������������������������������������������������������������������������������������� 323
Classical Dynamic Programming Examples������������������������������������������������������������������������������ 325
The Knapsack Problem�������������������������������������������������������������������������������������������������������� 325
Longest Common Subsequence������������������������������������������������������������������������������������������ 328
Coin Change������������������������������������������������������������������������������������������������������������������������ 330
Edit (Levenshtein) Distance������������������������������������������������������������������������������������������������� 334
Summary���������������������������������������������������������������������������������������������������������������������������������� 338

xiii
Table of Contents

Chapter 20: Bit Manipulation�������������������������������������������������������������������������������� 339


Bitwise Operators��������������������������������������������������������������������������������������������������������������������� 339
AND�������������������������������������������������������������������������������������������������������������������������������������� 340
OR���������������������������������������������������������������������������������������������������������������������������������������� 340
XOR�������������������������������������������������������������������������������������������������������������������������������������� 341
NOT�������������������������������������������������������������������������������������������������������������������������������������� 341
Left Shift������������������������������������������������������������������������������������������������������������������������������ 342
Right Shift���������������������������������������������������������������������������������������������������������������������������� 342
Zero-Fill Right Shift������������������������������������������������������������������������������������������������������������� 343
Number Operations������������������������������������������������������������������������������������������������������������������� 343
Addition������������������������������������������������������������������������������������������������������������������������������� 343
Subtraction�������������������������������������������������������������������������������������������������������������������������� 344
Multiplication����������������������������������������������������������������������������������������������������������������������� 345
Division�������������������������������������������������������������������������������������������������������������������������������� 347
Summary���������������������������������������������������������������������������������������������������������������������������������� 349

Index��������������������������������������������������������������������������������������������������������������������� 351

xiv
About the Author
Sammie Bae is a data engineer at Yelp and previously
worked for the data platform engineering team at
NVIDIA. He developed a deep interest in JavaScript
during an internship at SMART Technologies (acquired by
Foxconn), where he developed Node.js-based JavaScript
APIs for serial port communication between electronic
board drivers and a web application. Despite how relevant
JavaScript is to the modern software engineering industry,
currently no books besides this one teach algorithms and
data structures using JavaScript. Sammie understands how
difficult these computer science concepts are and aims to
provide clear and concise explanations in this book.

xv
About the Technical Reviewer
Phil Nash is a developer evangelist for Twilio, serving
developer communities in London and all over the world.
He is a Ruby, JavaScript, and Swift developer; Google
Developers Expert; blogger; speaker; and occasional brewer.
He can be found hanging out at meetups and conferences,
playing with new technologies and APIs, or writing open
source code.

xvii
Acknowledgments
Thank you, Phil Nash, for the valuable feedback that helped me improve the technical
content of this book with clear explanations and concise code.
Special thanks to the Apress team. This includes James Markham, Nancy Chen, Jade
Scard, and Chris Nelson. Finally, I want to thank Steve Anglin for reaching out to me to
publish with Apress.

xix
Introduction
The motivation for writing this book was the lack of resources available about data
structures and algorithms written in JavaScript. This was strange to me because
today many of the job opportunities for software development require knowledge of
JavaScript; it is the only language that can be used to write the entire stack, including the
front-end, mobile (native and hybrid) platforms, and back-end. It is crucial for JavaScript
developers to understand how data structures work and how to design algorithms to
build applications.
Therefore, this book aims to teach data structure and algorithm concepts from
computer science for JavaScript rather than for the more typical Java or C++. Because
JavaScript follows the prototypal inheritance pattern, unlike Java and C++ (which follow
the inheritance pattern), there are some changes in writing data structures in JavaScript.
The classical inheritance pattern allows inheritance by creating a blueprint-­like form
that objects follow during inheritance. However, the prototypal inheritance pattern
means copying the objects and changing their properties.
This book first covers fundamental mathematics for Big-O analysis and then lays out
the basic JavaScript foundations, such as primitive objects and types. Then, this book
covers implementations and algorithms for fundamental data structures such as linked
lists, stacks, trees, heaps, and graphs. Finally, more advanced topics such as efficient
string search algorithms, caching algorithms, and dynamic programming problems are
explored in great detail.

xxi
CHAPTER 1

Big-O Notation
O(1) is holy.
—Hamid Tizhoosh

Before learning how to implement algorithms, you should understand how to analyze
the effectiveness of them. This chapter will focus on the concept of Big-O notation for
time and algorithmic space complexity analysis. By the end of this chapter, you will
understand how to analyze an implementation of an algorithm with respect to both time
(execution time) and space (memory consumed).

Big-O Notation Primer


The Big-O notation measures the worst-case complexity of an algorithm. In Big-O
notation, n represents the number of inputs. The question asked with Big-O is the
following: “What will happen as n approaches infinity?”
When you implement an algorithm, Big-O notation is important because it tells you
how efficient the algorithm is. Figure 1-1 shows some common Big-O notations.

1
© Sammie Bae 2019
S. Bae, JavaScript Data Structures and Algorithms, https://doi.org/10.1007/978-1-4842-3988-9_1
Chapter 1 Big-O Notation

Figure 1-1. Common Big-O complexities

The following sections illustrate these common time complexities with some simple
examples.

Common Examples
O(1) does not change with respect to input space. Hence, O(1) is referred to as being
constant time. An example of an O(1) algorithm is accessing an item in the array by its
index. O(n) is linear time and applies to algorithms that must do n operations in the
worst-case scenario.
An example of an O(n) algorithm is printing numbers from 0 to n-1, as shown here:

1 function  exampleLinear(n) {
2                   for  (var  i = 0 ; i <  n; i++ ) {

2
Chapter 1 Big-O Notation

3                              console.log(i);
4                   }
5  }

Similarly, O(n2) is quadratic time, and O(n3) is cubic time. Examples of these
complexities are shown here:

1 function  exampleQuadratic(n) {
2                   for  (var  i = 0 ; i <  n; i++ ) {
3                                 console.log(i);
4                                for  (var  j =  i; j <  n; j++ ) {
5                                             console.log(j);
6                              }
7                   }
8  }

1 function  exampleCubic(n) {
2                   for  (var  i = 0 ; i <  n; i++ ) {
3                                  console.log(i);
4                                for  (var  j =  i; j <  n; j++ ) {
5                                              console.log(j);
6                                                  for  (var  k =  j;
j <  n; j++ ) {
7                                                          console.log(k);
8                                                  }
9                                }
10           }
11 }

Finally, an example algorithm of logarithmic time complexity is printing elements


that are a power of 2 between 2 and n. For example, exampleLogarithmic(10) will print
the following:

2,4,8,16,32,64

3
Chapter 1 Big-O Notation

The efficiency of logarithmic time complexities is apparent with large inputs such
as a million items. Although n is a million, exampleLogarithmic will print only 19
items because log2(1,000,000) = 19.9315686. The code that implements this logarithmic
behavior is as follows:

1 function exampleLogarithmic(n) {
2                   for (var i = 2 ; i <= n; i= i*2 ) {
3                          console.log(i);
4                  }
5 }

Rules of Big-O Notation


Let’s represent an algorithm’s complexity as f(n). n represents the number of inputs,
f(n)time represents the time needed, and f(n)space represents the space (additional
memory) needed for the algorithm. The goal of algorithm analysis is to understand the
algorithm’s efficiency by calculating f(n). However, it can be challenging to calculate f(n).
Big-O notation provides some fundamental rules that help developers compute for f(n).

• Coefficient rule: If f(n) is O(g(n)), then kf(n) is O(g(n)), for any


constant k > 0. The first rule is the coefficient rule, which eliminates
coefficients not related to the input size, n. This is because as n
approaches infinity, the other coefficient becomes negligible.

• Sum rule: If f(n) is O(h(n)) and g(n) is O(p(n)), then f(n)+g(n) is


O(h(n)+p(n)). The sum rule simply states that if a resultant time
complexity is a sum of two different time complexities, the resultant
Big-O notation is also the sum of two different Big-O notations.
• Product rule: If f(n) is O(h(n)) and g(n) is O(p(n)), then f(n)g(n) is
O(h(n)p(n)). Similarly, the product rule states that Big-O is multiplied
when the time complexities are multiplied.

• Transitive rule: If f(n) is O(g(n)) and g(n) is O(h(n)), then f(n) is


O(h(n)). The transitive rule is a simple way to state that the same time
complexity has the same Big-O.

4
Chapter 1 Big-O Notation

• Polynomial rule: If f(n) is a polynomial of degree k, then f(n) is


O(nk). Intuitively, the polynomial rule states that polynomial time
complexities have Big-O of the same polynomial degree.

• Log of a power rule: log(nk) is O(log(n)) for any constant k > 0. With
the log of a power rule, constants within a log function are also
ignored in Big-O notation.

Special attention should be paid to the first three rules and the polynomial rule
because they are the most commonly used. I’ll discuss each of those rules in the
following sections.

Coefficient Rule: “Get Rid of Constants”


Let’s first review the coefficient rule. This rule is the easiest rule to understand. It simply
requires you to ignore any non-input-size-related constants. Coefficients in Big-O are
negligible with large input sizes. Therefore, this is the most important rule of Big-O
notations.

If f(n) is O(g(n)), then kf(n) is O(g(n)), for any constant k > 0.

This means that both 5f(n) and f(n) have the same Big-O notation of O(f(n)).
Here is an example of a code block with a time complexity of O(n):

1   function a(n){
2       var count =0;
3       for (var i=0;i<n;i++){
4           count+=1;
5       }
6       return count;
7   }

This block of code has f(n) = n. This is because it adds to count n times. Therefore,
this function is O(n) in time complexity:

1   function a(n){
2       var count =0;
3       for (var i=0;i<5*n;i++){

5
Chapter 1 Big-O Notation

4           count+=1;
5       }
6       return count;
7   }

This block has f(n) = 5n. This is because it runs from 0 to 5n. However, the first two
examples both have a Big-O notation of O(n). Simply put, this is because if n is close to
infinity or another large number, those four additional operations are meaningless. It is
going to perform it n times. Any constants are negligible in Big-O notation.
The following code block demonstrates another function with a linear time
complexity but with an additional operation on line 6:

1   function a(n){
2       var count =0;
3       for (var i=0;i<n;i++){
4           count+=1;
5       }
6       count+=3;
7       return count;
8   }

Lastly, this block of code has f(n) = n+1. There is +1 from the last operation
(count+=3). This still has a Big-O notation of O(n). This is because that 1 operation is not
dependent on the input n. As n approaches infinity, it will become negligible.

Sum Rule: “Add Big-Os Up”


The sum rule is intuitive to understand; time complexities can be added. Imagine a
master algorithm that involves two other algorithms. The Big-O notation of that master
algorithm is simply the sum of the other two Big-O notations.

If f(n) is O(h(n)) and g(n) is O(p(n)), then f(n)+g(n) is O(h(n)+p(n)).

It is important to remember to apply the coefficient rule after applying this rule.

6
Chapter 1 Big-O Notation

The following code block demonstrates a function with two main loops whose time
complexities must be considered independently and then summed:

1   function a(n){
2       var count =0;
3       for (var i=0;i<n;i++){
4           count+=1;
5       }
6       for (var i=0;i<5*n;i++){
7           count+=1;
8       }
9       return count;
10   }

In this example, line 4 has f(n) = n, and line 7 has f(n) = 5n. This results in 6n.
However, when applying the coefficient rule, the final result is O(n) = n.

Product Rule: “Multiply Big-Os”


The product rule simply states how Big-Os can be multiplied.

If f(n) is O(h(n)) and g(n) is O(p(n)), then f(n)g(n) is O(h(n)p(n)).

The following code block demonstrates a function with two nested for loops for
which the product rule is applied:

1   function (n){
2       var count =0;
3       for (var i=0;i<n;i++){
4           count+=1;
5           for (var i=0;i<5*n;i++){
6               count+=1;
7           }
8       }
9       return count;
10   }

7
Chapter 1 Big-O Notation

In this example, f(n) = 5n*n because line 7 runs 5n times for a total of n iterations.
Therefore, this results in a total of 5n2 operations. Applying the coefficient rule, the result
is that O(n)=n2.

Polynomial Rule: “Big-O to the Power of k”


The polynomial rule states that polynomial time complexities have a Big-O notation of
the same polynomial degree.
Mathematically, it’s as follows:

If f(n) is a polynomial of degree k, then f(n) is O(nk).


The following code block has only one for loop with quadratic time complexity:

1   function a(n){
2       var count =0;
3       for (var i=0;i<n*n;i++){
4           count+=1;
5       }
6       return count;
7   }

In this example, f(n) = nˆ2 because line 4 runs n*n iterations.


This was a quick overview of the Big-O notation. There is more to come as you
progress through the book.

Summary
Big-O is important for analyzing and comparing the efficiencies of algorithms.
The analysis of Big-O starts by looking at the code and applying the rules to simplify
the Big-O notation. The following are the most often used rules:

• Eliminating coefficients/constants (coefficient rule)

• Adding up Big-Os (sum rule)


• Multiplying Big-Os (product rule)

• Determining the polynomial of the Big-O notation by looking at loops


(polynomial rule)

8
Chapter 1 Big-O Notation

Exercises
Calculate the time complexities for each of the exercise code snippets.

EXERCISE 1

1   function someFunction(n) {
2
3       for (var i=0;i<n*1000;i++) {
4           for (var j=0;j<n*20;j++) {
5               console.log(i+j);
6           }
7       }
8
9   }

EXERCISE 2

1   function someFunction(n) {
2
3       for (var i=0;i<n;i++) {
4           for (var j=0;j<n;j++) {
5               for (var k=0;k<n;k++) {
6                   for (var l=0;l<10;l++) {
7                       console.log(i+j+k+l);
8                   }
9               }
10           }
11       }
12
13   }

9
Chapter 1 Big-O Notation

EXERCISE 3

1   function someFunction(n) {
2
3       for (var i=0;i<1000;i++) {
4           console.log("hi");
5       }
6
7   }

EXERCISE 4

1   function someFunction(n) {
2
3       for (var i=0;i<n*10;i++) {
4           console.log(n);
5       }
6
7   }

EXERCISE 5

1   function someFunction(n) {
2
3       for (var i=0;i<n;i*2) {
4           console.log(n);
5       }
6
7   }

10
Chapter 1 Big-O Notation

EXERCISE 6

1   function someFunction(n) {
2
3       while (true){
4           console.log(n);
5       }
6   }

Answers
1. O(n2)
There are two nested loops. Ignore the constants in front of n.

2. O(n3)
There are four nested loops, but the last loop runs only until 10.

3. O(1)
Constant complexity. The function runs from 0 to 1000. This does
not depend on n.

4. O(n)
Linear complexity. The function runs from 0 to 10n. Constants are
ignored in Big-O.
5. O(log2n)
Logarithmic complexity. For a given n, this will operate only log2n
times because i is incremented by multiplying by 2 rather than
adding 1 as in the other examples.

6. O(∞)

Infinite loop. This function will not end.

11
CHAPTER 2

JavaScript: Unique Parts


This chapter will briefly discuss some exceptions and cases of JavaScript’s syntax and
behavior. As a dynamic and interpreted programming language, its syntax is different
from that of traditional object-oriented programming languages. These concepts are
fundamental to JavaScript and will help you to develop a better understanding of the
process of designing algorithms in JavaScript.

J avaScript Scope
The scope is what defines the access to JavaScript variables. In JavaScript, variables
can belong to the global scope or to the local scope. Global variables are variables that
belong in the global scope and are accessible from anywhere in the program.

Global Declaration: Global Scope


In JavaScript, variables can be declared without using any operators. Here’s an example:

1  test = "sss";
2  console.log(test); // prints "sss"

However, this creates a global variable, and this is one of the worst practices in
JavaScript. Avoid doing this at all costs. Always use var or let to declare variables.
Finally, when declaring variables that won’t be modified, use const.

Declaration with var: Functional Scope


In JavaScript, var is one keyword used to declare variables. These variable declarations
“float” all the way to the top. This is known as variable hoisting. Variables declared at the
bottom of the script will not be the last thing executed in a JavaScript program during
runtime.
13
© Sammie Bae 2019
S. Bae, JavaScript Data Structures and Algorithms, https://doi.org/10.1007/978-1-4842-3988-9_2
Chapter 2 JavaScript: Unique Parts

Here’s an example:

1  function scope1(){
2          var top = "top";
3          bottom = "bottom";
4          console.log(bottom);
5
6          var bottom;
7  }
8  scope1(); // prints "bottom" - no error

How does this work? The previous is the same as writing the following:

1  function scope1(){
2          var top = "top";
3          var  bottom;
4          bottom = "bottom"
5          console.log(bottom);
6  }
7  scope1(); // prints "bottom" - no error

The bottom variable declaration, which was at the last line in the function, is floated
to the top, and logging the variable works.
The key thing to note about the var keyword is that the scope of the variable is the
closest function scope. What does this mean?
In the following code, the scope2 function is the function scope closest to the print
variable:

1  function scope2(print){
2          if(print){
3                   var insideIf = '12';
4          }
5          console.log(insideIf);
6  }
7  scope2(true); // prints '12' - no error

14
Chapter 2 JavaScript: Unique Parts

To illustrate, the preceding function is equivalent to the following:

1  function scope2(print){
2          var insideIf;
3
4          if(print){
5                   insideIf = '12';
6          }
7          console.log(insideIf);
8  }
9  scope2(true); // prints '12' - no error

In Java, this syntax would have thrown an error because the insideIf variable is
generally available only in that if statement block and not outside it.
Here’s another example:

1  var a = 1;
2  function four() {
3    if (true) {
4      var a = 4;
5    }
6
7    console.log(a); // prints '4'
8  }

4 was printed, not the global value of 1, because it was redeclared and available in
that scope.

Declaration with let: Block Scope


Another keyword that can be used to declare a variable is let. Any variables declared
this way are in the closest block scope (meaning within the {} they were declared in).

1  function scope3(print){
2          if(print){
3                   let insideIf = '12';
4          }

15
Chapter 2 JavaScript: Unique Parts

5          console.log(insideIf);
6  }
7  scope3(true); // prints ''

In this example, nothing is logged to the console because the insideIf variable is
available only inside the if statement block.

Equality and Types


JavaScript has different data types than in traditional languages such as Java. Let’s
explore how this impacts things such as equality comparison.

Variable Types
In JavaScript, there are seven primitive data types: boolean, number, string, undefined,
object, function, and symbol (symbol won’t be discussed). One thing that stands out
here is that undefined is a primitive value that is assigned to a variable that has just been
declared. typeof is the primitive operator used to return the type of a variable.

1  var is20 = false; // boolean


2  typeof is20; // boolean
3
4  var  age = 19;
5  typeof age; // number
6
7  var  lastName = "Bae";
8  typeof lastName; // string
9
10  var fruits = ["Apple", "Banana", "Kiwi"];
11  typeof fruits; // object
12
13  var me = {firstName:"Sammie", lastName:"Bae"};
14  typeof me; // object
15
16  var nullVar = null;
17  typeof nullVar; // object
18
16
Chapter 2 JavaScript: Unique Parts

19  var function1 = function(){


20          console.log(1);
21  }
22  typeof function1 // function
23
24  var blank;
25  typeof blank; // undefined

Truthy/Falsey Check
True/false checking is used in if statements. In many languages, the parameter inside
the if() function must be a boolean type. However, JavaScript (and other dynamically
typed languages) is more flexible with this. Here’s an example:

1  if(node){
2          ...
3  }

Here, node is some variable. If that variable is empty, null, or undefined, it will be
evaluated as false.
Here are commonly used expressions that evaluate to false:

• false

• 0

• Empty strings ('' and "")


• NaN

• undefined

• null

Here are commonly used expressions that evaluate to true:

• true

• Any number other than 0

• Non-empty strings

• Non-empty object

17
Chapter 2 JavaScript: Unique Parts

Here’s an example:

1  var printIfTrue = ";


2
3  if (printIfTrue) {
4          console.log('truthy');
5  } else {
6          console.log('falsey'); // prints 'falsey'
7  }

=== vs ==
JavaScript is a scripting language, and variables are not assigned a type during
declaration. Instead, types are interpreted as the code runs.
Hence, === is used to check equality more strictly than ==. === checks for both the
type and the value, while == checks only for the value.

1  "5" == 5 // returns true


2  "5" === 5 // returns false

"5" == 5 returns true because "5" is coerced to a number before the comparison.
On the other hand, "5" === 5 returns false because the type of "5" is a string, while 5 is
a number.

Objects
Most strongly typed languages such as Java use isEquals() to check whether two objects
are the same. You may be tempted to simply use the == operator to check whether two
objects are the same in JavaScript.
However, this will not evaluate to true.

1  var o1 = {};
2  var o2 = {};
3
4  o1 == o2 // returns false
5  o1 === o2 // returns false

18
Chapter 2 JavaScript: Unique Parts

Although these objects are equivalent (same properties and values), they are not
equal. Namely, the variables have different addresses in memory.
This is why most JavaScript applications use utility libraries such as lodash1 or
underscore,2 which have the isEqual(object1, object2) function to check two objects
or values strictly. This occurs via implementation of some property-based equality
checking where each property of the object is compared.
In this example, each property is compared to achieve an accurate object equality result.

1  function isEquivalent(a, b) {
2      // arrays of property names
3      var aProps = Object.getOwnPropertyNames(a);
4      var bProps = Object.getOwnPropertyNames(b);
5
6      // If their property lengths are different, they're different objects
7      if (aProps.length != bProps.length) {
8          return false;
9      }
10
11      for (var  i = 0; i < aProps.length; i++) {
12          var propName = aProps[i];
13
14          // If the values of the property are different, not equal
15          if (a[propName] !== b[propName]) {
16              return false;
17          }
18      }
19
20     // If everything matched, correct
21     return  true;
22  }
23  isEquivalent({'hi':12},{'hi':12}); // returns true

1
h ttps://lodash.com/
2
http://underscorejs.org/

19
Chapter 2 JavaScript: Unique Parts

However, this would still work for objects that have only a string or a number as the
property.

1  var obj1 = {'prop1': 'test','prop2': function (){} };


2  var obj2 = {'prop1': 'test','prop2': function (){} };
3
4  isEquivalent(obj1,obj2); // returns false

This is because functions and arrays cannot simply use the == operator to check for
equality.

1  var function1 = function(){console.log(2)};


2  var function2 = function(){console.log(2)};
3  console.log(function1 == function2); // prints 'false'

Although the two functions perform the same operation, the functions have
different addresses in memory, and therefore the equality operator returns false.
The primitive equality check operators, == and ===, can be used only for strings and
numbers. To implement an equivalence check for objects, each property in the object
needs to be checked.

Summary
JavaScript has a different variable declaration technique than most programming
languages. var declares the variable within the function scope, let declares the variable
in the block scope, and variables can be declared without any operator in the global
scope; however, global scope should be avoided at all times. For type checking, typeof
should be used to validate the expected type. Finally, for equality checks, use == to check
the value, and use === to check for the type as well as the value. However, use these only
on non-object types such as numbers, strings, and booleans.

20
CHAPTER 3

JavaScript Numbers
This chapter will focus on JavaScript number operations, number representation, Number
objects, common number algorithms, and random number generation. By the end of
this chapter, you will understand how to work with numbers in JavaScript as well as how
to implement prime factorization, which is fundamental for encryption.
Number operations of a programming language allow you to compute numerical
values. Here are the number operators in JavaScript:

+ : addition
- : subtraction
/ : division
* : multiplication
% : modulus

These operators are universally used in other programming languages and are not
specific to JavaScript.

N
 umber System
JavaScript uses a 32-bit floating-point representation for numbers, as shown in Figure 3-­1.
In this example, the value is 0.15625. The sign bit (the 31st bit) indicates that the number
is negative if the sign bit is 1. The next 8 bits (the 30th to 23rd bits) indicate the exponent
value, e. Finally, the remaining 23 bits represent the fraction value.

Figure 3-1. The 32-bit floating-point number system


21
© Sammie Bae 2019
S. Bae, JavaScript Data Structures and Algorithms, https://doi.org/10.1007/978-1-4842-3988-9_3
Chapter 3 JavaScript Numbers

With the 32 bits, the value is computed by this esoteric formula:

æ 23
ö
value = ( -1) ´ 2e -127 ´ ç 1 + åb23 -t 2 -t ÷
sign

è t =1 ø

Figure 3-1 shows the following break down of the 32 bits:


sign = 0
e = (0111100)2 = 124 (in base 10)
23
1 + åb23 -i 2 -i = 1 + 0 + 0.25 + 0
i =1

This results in the following:

value = 1 x 2124-127 x 1.25 = 1 x 2-3 x 1.25 = 0.15625

With decimal fractions, this floating-point number system causes some rounding
errors in JavaScript. For example, 0.1 and 0.2 cannot be represented precisely.
Hence, 0.1 + 0.2 === 0.3 yields false.

1  0.1 + 0.2 === 0.3; // prints 'false'

To really understand why 0.1 cannot be represented properly as a 32-bit floating-­


point number, you must understand binary. Representing many decimals in binary
requires an infinite number of digits. This because binary numbers are represented by 2n
where n is an integer.
While trying to calculate 0.1, long division will go on forever. As shown in Figure 3-­2,
1010 represents 10 in binary. Trying to calculate 0.1 (1/10) results in an indefinite
number of decimal points.

22
Chapter 3 JavaScript Numbers

Figure 3-2. Long division for 0.1

JavaScript Number Object


Luckily, there are some built-in properties of the Number object in JavaScript that help
work around this.

Integer Rounding
Since JavaScript uses floating point to represent all numbers, integer division does not work.
Integer division in programming languages like Java simply evaluates division
expressions to their quotient.
For example, 5/4 is 1 in Java because the quotient is 1 (although there is a remainder
of 1 left). However, in JavaScript, it is a floating point.

1  5/4; // 1.25
23
Chapter 3 JavaScript Numbers

This is because Java requires you to explicitly type the integer as an integer.
Hence, the result cannot be a floating point. However, if JavaScript developers want to
implement integer division, they can do one of the following:

Math.floor - rounds down to nearest integer


Math.round - rounds to nearest integer
Math.ceil  - rounds up to nearest integer

Math.floor(0.9); // 0
Math.floor(1.1); // 1

Math.round(0.49); // 0
Math.round(0.5); // 1

Math.round(2.9); // 3
Math.ceil(0.1); // 1 Math.ceil(0.9); // 1 Math.ceil(21);
// 21 Math.ceil(21.01); // 22

Number.EPSILON
Number.EPSILON returns the smallest interval between two representable numbers.
This is useful for the problem with floating-point approximation.

1  function numberEquals(x, y) {
2      return Math.abs(x - y) < Number.EPSILON;
3  }
4
5  numberEquals(0.1 + 0.2, 0.3); // true

This function works by checking whether the difference between the two numbers
are smaller than Number.EPSILON. Remember that Number.EPSILON is the smallest
difference between two representable numbers. The difference between 0.1+0.2 and 0.3
will be smaller than Number.EPSILON.

Maximums
Number.MAX_SAFE_INTEGER returns the largest integer.

1  Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2; // true

24
Chapter 3 JavaScript Numbers

This returns true because it cannot go any higher. However, it does not work for
floating-point decimals.

1  
Number.MAX_SAFE_INTEGER + 1.111 === Number.MAX_SAFE_INTEGER + 2.022;
// false

Number.MAX_VALUE returns the largest floating-point number possible.


Number.MAX_VALUE is equal to 1.7976931348623157e+308.

1  Number.MAX_VALUE + 1 === Number.MAX_VALUE + 2; // true

Unlike like Number.MAX_SAFE_INTEGER, this uses double-precision floating-point


representation and works for floating points as well.

1  Number.MAX_VALUE + 1.111 === Number.MAX_VALUE + 2.022; // true

Minimums
Number.MIN_SAFE_INTEGER returns the smallest integer.
Number.MIN_SAFE_INTEGER is equal to -9007199254740991.

1  Number.MIN_SAFE_INTEGER - 1 === Number.MIN_SAFE_INTEGER - 2; // true

This returns true because it cannot get any smaller. However, it does not work for
floating-point decimals.

1  Number.MIN_SAFE_INTEGER - 1.111 === Number.MIN_SAFE_INTEGER - 2.022;


// false

Number.MIN_VALUE returns the smallest floating-point number possible.


Number.MIN_VALUE is equal to 5e-324. This is not a negative number since it is the
smallest floating-point number possible and means that Number.MIN_VALUE is actually
bigger than Number.MIN_- SAFE_INTEGER.
Number.MIN_VALUE is also the closest floating point to zero.

1  Number.MIN_VALUE - 1 == -1; // true

This is because this is similar to writing 0 - 1 == -1.

25
Chapter 3 JavaScript Numbers

Infinity
The only thing greater than Number.MAX_VALUE is Infinity, and the only thing smaller
than Number.MAX_SAFE_INTEGER is -Infinity.

1  Infinity > Number.MAX_SAFE_INTEGER; // true


2  -Infinity < Number.MAX_SAFE_INTEGER // true;
3  -Infinity -32323323 == -Infinity -1; // true

This evaluates to true because nothing can go smaller than -Infinity.

Size Summary
This inequality summarizes the size of JavaScript numbers from smallest (left) to
largest (right):

-Infinity < Number.MIN_SAFE_INTEGER < Number.MIN_VALUE < 0 < Number.MAX_


SAFE_IN- TEGER < Number.MAX_VALUE < Infinity

Number Algorithms
One of the most discussed algorithms involving numbers is for testing whether a number
is a prime number. Let’s review this now.

Primality Test
A primality test can be done by iterating from 2 to n, checking whether modulus division
(remainder) is equal to zero.

1  function isPrime(n){
2      if (n <= 1) {
3              return false;
4      }
5
6      // check from 2 to n-1
7      for (var i=2; i<n; i++) {
8              if (n%i == 0) {
9                      return false;
10          }
26
Chapter 3 JavaScript Numbers

11      }
12
13      return true;
14  }

Time Complexity: O(n)


The time complexity is O(n) because this algorithm checks all numbers from 0 to n.
This is an example of an algorithm that can be easily improved. Think about how this
method iterates through 2 to n. Is it possible to find a pattern and make the algorithm
faster? First, any multiple of 2s can be ignored, but there is more optimization possible.
Let’s list some prime numbers.

2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97

This is difficult to notice, but all primes are of the form 6k ± 1, with the exception of
2 and 3 where k is some integer. Here’s an example:

5 = (6-1) , 7 = ((1*6) + 1), 13 = ((2*6) + 1) etc

Also realize that for testing the prime number n, the loop only has to test until the
square root of n. This is because if the square root of n is not a prime number, n is not a
prime number by mathematical definition.

1  function isPrime(n){
2      if (n <= 1) return false;
3      if (n <= 3) return true;
4
5      // This is checked so that we can skip
6      // middle five numbers in below loop
7      if (n%2 == 0 || n%3 == 0) return false;
8
9      for (var i=5; i*i<=n; i=i+6){
10          if (n%i == 0 || n%(i+2) == 0)
11             return false;
12      }
13
14      return true;
15  }

27
Chapter 3 JavaScript Numbers

Time Complexity: O(sqrt(n))


This improved solution cuts the time complexity down significantly.

P
 rime Factorization
Another useful algorithm to understand is for determining prime factorization of a
number. Prime numbers are the basis of encryption (covered in Chapter 4) and hashing
(covered in Chapter 11), and prime factorization is the process of determining which
prime numbers multiply to a given number. Given 10, it would print 5 and 2.

1  function primeFactors(n){
2          // Print the number of 2s that divide n
3          while (n%2 == 0) {
4              console.log(2);
5              n = n/2;
6          }
7
8          // n must be odd at this point. So we can skip one element
(Note i = i +2)
9          for (var i = 3; i*i <= n; i = i+2) {
10             // While i divides n, print i and divide n
11              while (n%i == 0) {
12                  console.log(i);
13                  n = n/i;
14              }
15          }
16          //This condition is to handle the case when n is a prime number
17          //greater than 2
18          if (n > 2) {
19                  console.log(n);
20          }
21  }
22  primeFactors(10); // prints '5' and '2'

28
Chapter 3 JavaScript Numbers

Time Complexity: O(sqrt(n))


This algorithm works by printing any number that is divisible by i without a
remainder. In the case that a prime number is passed into this function, it would be
handled by printing whether n is greater than 2.

Random Number Generator


Random number generation is important to simulate conditions. JavaScript has a built-­in
function for generating numbers: Math.random().

Math.random() returns a float between 0 and 1.

You may wonder how you get random integers or numbers greater than 1.
To get floating points higher than 1, simply multiply Math.random() by the range.
Add or subtract from it to set the base.

Math.random() * 100; // floats between 0  and  100


Math.random() * 25 + 5; // floats between 5  and  30
Math.random() * 10 - 100; // floats between -100 and -90

To get random integers, simply use Math.floor(), Math.round(), or Math.ceil() to


round to an integer.

Math.floor(Math.random() * 100); // integer between 0 and 99


Math.round(Math.random() * 25) + 5; // integer between 5 and 30
Math.ceil(Math.random() * 10) - 100; // integer between -100 and -90

Exercises
1. Given three numbers x, y, and p, compute (xˆy) % p. (This is
modular exponentiation.)
Here, x is the base, y is exponent, and p is the modulus.
Modular exponentiation is a type of exponentiation performed
over a modulus, which is useful in computer science and used in
the field of public-key encryption algorithms.
At first, this problem seems simple. Calculating this is a one-line
solution, as shown here:
29
Chapter 3 JavaScript Numbers

1  function modularExponentiation ( base, exponent, modulus ) {


2          return Math.pow(base,exponent) % modulus;
3  }

This does exactly what the question asks. However, it cannot


handle large exponents.
Remember that this is implemented with encryption algorithms.
In strong cryptography, the base is often at least 256 bit (78 digits).
Consider this case, for example:
Base: 6x1077, Exponent: 27, Modulus: 497
In this case, (6x1077)27 is a very large number and cannot be stored
in a 32-bit floating point.
There is another approach, which involves some math. One must
observe the following mathematical property:
For arbitrary a and b,

c % m = (a  b) % m
c % m = [(a % m)  (b % m)] % m

Using this mathematical property, you can iterate 1 to the


exponent, recalculating each time by multiplying the current
modulus value with the last.

Here is the pseudocode:

1  Set value = 1, current exponent = 0.


2  Increment current exponent by 1.
3  Set value = (base  value) mod modulus until current
exponent is reached exponent

Example: Base: 4, Exponent: 3, Modulus: 5

4ˆ3 % 5 = 64 % 5 = 4

value = (lastValue x base ) % modulus:


value = (1 x 4) % 5 = 4 % 5 = 4

30
Chapter 3 JavaScript Numbers

value = (4 x 4) % 5 = 16 % 5 = 1

value = (1 x 4) % 5 = 4 % 5 = 4

Finally, here is the code:

1  function modularExponentiation ( base, exponent, modulus ) {


2          if (modulus == 1) return 0;
3
4          var value = 1;
5
6          for ( var i=0; i<exponent; i++ ){
7                  value = (value * base) % modulus;
8          }
9          return value;
10  }

Time Complexity: O(n)

The time complexity is O(n) where n is equal to the exponent value.

2. Print all primes less than n.

To do this, use the isPrime function covered in this chapter.


Simply iterate from 0 to n and print any prime numbers where
isPrime() evaluates to true.

1  function allPrimesLessThanN(n){
2          for (var i=0; i<n; i++) {
3                  if (isPrime(i)){
4                          console.log(i);
5                  }
6          }
7  }
8
9  function isPrime(n){
10      if (n <= 1) return false;
11      if (n <= 3) return true;
12

31
Chapter 3 JavaScript Numbers

13      // This is checked so that we can skip


14      // middle five numbers in below loop
15      if (n%2 == 0 || n%3 == 0) return false;
16
17      for (var i=5; i*i<=n; i=i+6){
18          if (n%i == 0 || n%(i+2) == 0)
19             return false;
20      }
21
22      return true;
23  }
24
25  allPrimesLessThanN(15);
26
27  // prints 2, 3, 5, 7, 11, 13

Time Complexity: O(nsqrt(n))

This is because isPrime (covered earlier in this chapter) with a


time complexity of O(sqrt(n)) is run n times.

3. Check for a set of prime factors.

Let’s define ugly numbers as those whose only prime factors are
2, 3, or 5. The sequence 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, … shows the
first 11 ugly numbers. By convention, 1 is included.
To do this, divide the number by the divisors (2, 3, 5) until it
cannot be divided without a remainder. If the number can be
divided by all the divisors, it should be 1 after dividing everything.

1  function maxDivide (number, divisor) {


2          while (number % divisor == 0) {
3                  number /= divisor;
4          }
5          return number;
6  }
7
8  function isUgly (number){
9          number = maxDivide(number, 2);
32
Chapter 3 JavaScript Numbers

10          number = maxDivide(number, 3);


11          number = maxDivide(number, 5);
12          return number === 1;
13  }

Iterate this over n, and now the list of ugly numbers can be
returned.

1  function arrayNUglyNumbers (n) {


2          var counter = 0, currentNumber = 1,
uglyNumbers = [];
3
4          while ( counter != n ) {
5
6                  if ( isUgly(currentNumber) ) {
7                          counter++;
8                          uglyNumbers.push(currentNumber);
9                  }
10
11                  currentNumber++;
12          }
13
14          return uglyNumbers;
15  }

Time Complexity for maxDivide(number, divisor):


O(logdivisor(number))
The time complexity of maxDivide is a logarithmic function which
depends on divisor and the number. When testing primes of 2,
3, and 5, the logarithmic of 2 (log2 (n)) yields the highest time
complexity.

Time Complexity for isUgly: O(log2(n))


Time Complexity for arrayNUglyNumbers: O(n(log2(n)))
The isUgly function is limited by the time complexity of maxDivide(number, 2).
Hence, arrayNUglyNumbers has n times that time complexity.

33
Other documents randomly have
different content
Twelfth-Night, the last of Shakspeare's dramas, probable date
of, ii. 531-533.
Its general character, and conduct of the fable, 534.

Illustrations of this drama in the present work.

Act i. scene 4., i. 436.


scene 5., ii. 117.
Act ii. scene 3., i. 578.
scene 4., i. 574. ii. 534.

scene 5., ii. 533.


Act iii. scene 1., i. 270.
scene 4., i. 334. ii. 118. 532, 533.
Act iv. scene 3., i. 221.
Act v. scene 1., i. 221.

Two Gentlemen of Verona, date of, ii. 367.


Probable source of its fable, ibid. 368.
Remarks on the delineation of its characters, particularly that
of Julia, 368, 369.

Illustrations of this drama in the present work.

Act i. scene 2., ii. 360.


Act ii. scene 1., i. 341. ii. 581.
scene 2., i. 220.
scene 6., i. 175.
scene 7., ii. 370.
Act iii. scene 1., ii. 97.
Act iv. scene 1., i. 163. ii. 369.
scene 4., ii. 93.

Twyne (John), the topographer, notice of, i. 480.


Twyne (Thomas), a minor poet of the age of Shakspeare, i. 704.
Tye (Christopher), a minor poet of the age of Shakspeare, i.
704.
Typography, remarks on the style of, in Queen Elizabeth's reign,
i. 437.
Beautiful specimens of decorative printing, 438.
Tyrwhitt (Mr.), conjecture of, respecting the date of
Shakspeare's Romeo and Juliet, ii. 356, 357.
And of Twelfth-Night, 531, 532.

U
Underdonne (Thomas), a minor poet of the age of Shakspeare,
i. 704.
Upstart country-squire or knight, character of, i. 81.

V
"Valentine and Orson," romance of, cited by Shakspeare, i. 572.
Notice of a curious edition of, 571, 572.
Its extensive popularity, 572.
Valentine's Day, origin of the superstitions concerning, i. 324.
Custom of choosing lovers ascribed to Madame Royale, 324,
325.
Supposed to be of pagan origin, 325.
Modes of ascertaining Valentines for the current year, 326.
The poor feasted on this day, 327.
Vallans (William), a minor poet of the age of Shakspeare, i. 705.
Vaughan's (W.) "Golden Grove," a collection of essays, i. 513.
Character of, with specimens of his style, 514.
Vaux (Lord), specimen of the poems of, i. 713.
Vennard (Richard), a minor poet of the age of Shakspeare, i.
705.
Venice one of the sources of English fashions in the age of
Shakspeare, ii. 94.
Venus and Adonis, a poem of Shakspeare, probable date of, i.
426, 427.
Notice of the "Editio Princeps," ii. 20, 21.
Dedicated to the Earl of Southampton, 3.
Proofs of its melody and beauty of versification, 21-23.
Singular force and beauty of its descriptions, 24-26.
Similes, 26.
And astonishing powers of Shakspeare's mind, 27.
This poem inferior to its classical prototypes, ibid.
Complimentary verses on this poem, addressed to
Shakspeare, 28-30.
Its meretricious tendency censured by contemporary writers,
31.
Popularity of this poem, 31. note [31:A].
Notice of its principal editions, 32.
Versification of the poetry of the Elizabethan age examined, i.
597.
Remarks on the versification of Sir John Beaumont, 601.
Of Browne, 603.
Of Chalkhill, 606.
Of Chapman, 608.
Of Daniel, 612.
Of Davies, 613.
Of Davors, 614.
Of Donne, 615.
Of Drayton, 616, 617.
Of Drummond, 618.
Of Fairefax, 619.
Of the two Fletchers, 620, 621.
Of Gascoigne, 626.
Of Bishop Hall, 628, 629.
Of Dr. Lodge, 632-635.
Of Marston, 637.
Of Spenser, 648.
Of the Earl of Stirling, 651.
Of Sylvester, 653.
Of Watson, 661.
Of Willobie, 665, 666.
Of Shakspeare's Venus and Adonis, ii. 21-23.
Of his Rape of Lucrece, 33-36.
Of Spenser's sonnets, 55.
Of Shakspeare's sonnets, 77-82.
Of Peele, 240. note.
Of the Two Gentlemen of Verona, 369.
Verstegan (Richard), a minor poet of the age of Shakspeare, i.
705.
Vincent (St.), supposed influence of his day, i. 350.
Virtue loved and cherished by Shakspeare's fairies, ii. 339, 340.
Virtus post funera vivit, whimsical translation of, i. 238, 239.
Voltaire's calumnies on Shakspeare refuted, ii. 553, 554.
Volumnia, remarks on the character of, ii. 494, 495.
Vortigern and Rowena, anecdote of, i. 127, 128.
Vows, how made by knights in the age of chivalry, i. 552.
Voyages and Travels, collections of, published in the time of
Shakspeare, i. 477-479.

W
Wager (Lewis), a dramatic poet, notice of, ii. 234.
Waists of great length, fashionable in the age of Shakspeare, ii.
97.
Wakes, origin of, i. 209.
Degenerate into licentiousness, 210.
Verses on, by Tusser, ibid.
And by Herrick, 211, 212.
Frequented by pedlars, 212.
Village-wakes still kept up in the North, 213.
Walton's "Complete Angler," errata in, i. 293. note.
Encomium on, 297. note.
Wapul (George), a dramatic writer in the time of Elizabeth, ii.
237.
Wardrobes (ancient), account of, ii. 91, 92.
Notice of theatrical wardrobes, in the time of Shakspeare,
220, 221.
Warner (William), biographical notice of, i. 658.
Critical remarks on his "Albion's England," 659, 660.
Quotations from that poem illustrative of old English
manners and customs, i. 104, 105. 118, 119. 135. 143. note.
147. note.
Warnings (preternatural) of death or danger, i. 351-354.
Warren (William), a minor poet of the age of Shakspeare, i. 705.
Warton (Dr.), observations of, on the "Gesta Romanorum," i.
536, 537.
On Fenton's collection of Italian novels, 542.
On the satires of Bishop Hall, 628, 629.
On the merits of Harington, 629.
On the satires of Marston, 637.
Washing of hands, why necessary before dinner in the age of
Elizabeth, ii. 145.
Wassail, origin of the term, i. 127.
Synonymous with feasting, 129.
Wassail-bowl, ingredients in, i. 127.
Description of an ancient one, 128.
Allusions to, in Shakspeare, 129, 130.
And by Milton, 131.
The peg-tankard, a species of wassail-bowl, 131. note.
Watch-lights, an article of furniture in Shakspeare's time, ii. 117.
Water-closets, by whom invented, ii. 135. note.
Water-spirits, different classes of, ii. 522, 523.
Watson (Thomas), a poet of the Elizabethan age, critical notice
of his works, particularly of his sonnets, i. 660-662., ii. 54.
Said by Mr. Steevens to be superior to Shakspeare as a
writer of sonnets, i. 663.
List of his other poems, ibid.
Weather, prognostications of, from particular days, i. 323.
Webbe (William), account of his "Discourse of English Poetrie,"
i. 463, 464.
Its extreme rarity and high price, 463. note.
First and second Eclogues of Virgil, 705.
Webster (William), a minor poet of the age of Shakspeare, i.
705.
Webster (John), estimate of the merits of, as a dramatic poet, ii.
564, 565.
Illustrations of his plays, viz.:
Vittoria Corombona, i. 233, 234. 237, 238. 396.
Dutchess of Malfy, i. 351.
Wedderburn, a minor poet of the age of Shakspeare, i. 705.
Weddings, how celebrated, i. 223-226.
Description of a rustic wedding, 227-229.
Weever (John), a minor poet of the age of Shakspeare, i. 705.
Bibliographical notice of his "Epigrammes," ii. 371.
Verses of, on Shakspeare's Venus and Adonis, ii. 28.
Epigram of, on Shakspeare's poems and plays, 372.
Wells, superstitious notions concerning, i. 391-393.
Wenman (Thomas), a minor poet of the age of Shakspeare, i.
706.
Wharton's "Dreame," a poem, i. 706.
Whetstone's (George), collection of tales, notice of, i. 543.
His "Rocke of Regard," and other poems, 706.
Account of the prevalence of gaming in his time, ii. 157, 158.
Notice of his dramatic productions, 238.
His "Promos and Cassandra," the immediate source of
Shakspeare's Measure for Measure, 453.
Whipping-tops anciently kept for public use, i. 312.
Whitney (George), a minor poet of the age of Shakspeare, i.
706.
Whitsuntide, festival of, how celebrated, i. 175-180.
Morris-dance, its accompaniment, ibid.
With Maid Marian, 179.
Whitsun plays, 181.
Wieland's "Oberon," character of, i. 564. note.
Wild-goose-chace, a kind of horse race, notice of, i. 304, 305.
Wilkinson (Edward), a minor poet of the age of Shakspeare, i.
706.
Will of John Shakspeare, account of the discovery of, i. 8, 9.
Copy of it, 9-14.
First published by Mr. Malone, ibid.
Its authenticity subsequently doubted by him, 15.
Confirmed by Mr. Chalmers, ibid.
Additional reasons for its authenticity, 16.
Its probable date, ibid.
Will of William Shakspeare, ii. 627-632.
Observations on it, 612-614.
Willet (Andrew), "Emblems" of, i. 706.
Willobie (Henry), a poet of the Elizabethan age, critical notice
of, i. 663, 664.
Origin of his "Avisa," 665.
Character of that work, 665, 666.
Commendatory verses in, on Shakspeare's Rape of Lucrece,
ii. 40.
Will-o'-wisp, superstitious notions concerning, i. 399, 400.
Willymat's (William) "Prince's Looking Glass," i. 706.
Wilmot (Robert), a dramatic poet in the reign of Elizabeth,
character of, ii. 234, 235.
Wilson (Thomas), observations of, on the corruptions of the
English language, in the time of James I., i. 440, 441.
Proofs that his "Rhetoricke" had been studied by
Shakspeare, 472-474.
Wincot ale celebrated for its strength, i. 48.
Epigram on, 48, 49.
Allusions to this place in Shakspeare's plays, 50.
Wine, enormous consumption of, in the age of Shakspeare, ii.
129.
Foreign wines then drunk, 130-132.
Presents of, usually sent from one room in a tavern to
another, 134.
Winter evening's conversations of the sixteenth century,
superstitious subjects of, i. 316-322.
Winter's Tale, probable date of, ii. 495-497.
Its general character, 497-500.
And probable source, 498.
Passages of this drama illustrated in the present work.

Act i. scene 2., i. 223. ii. 171. 495.

Act ii. scene 1., i. 107. 316.


Act iv. scene 2., i. 35. 183. 582.

scene 3., i. 165. 181. 184. 212. 213. 582-584. ii. 499,
500.
Act v. scene 2., i. 584. ii. 499.

scene 3., ii. 99.

Wit-combats of Shakspeare and Jonson, and their associates,


notice of, ii. 592, 593.
Witchcraft made felony by Henry VIII., ii. 474.
Supposed increase of witches in the time of Queen Elizabeth,
ii. 474, 475.
General prevalence of this infatuation, 475.
Increased under the reign of James I., 476.
Cruel act of parliament against witches, 477.
Description of the wretched persons who were ordinarily
supposed to be witches, 478-480.
Exquisite description of a witch's abode by Spenser, 480.
Enumeration of the feats witches were supposed to be
capable of performing, 481-483.
Nature of their supposed compact with the devil, 483-485.
Application of this superstition by Shakspeare to dramatic
purposes in his Macbeth, 487-489.
Wither (George), biographical notice of, i. 666.
Critical observations on his satires, 667.
And on his "Juvenilia," 668, 669.
List of his other pieces, with remarks, 669-671.
Verses of, on Hock-Day, i. 151. note.
Withold (St.), supposed influence of, against the nightmare, i.
347-349.
Wives, supposed appearance of future, on Midsummer-Eve, i.
332-334.
And on All-Hallow-Eve, 344-347.
Wives' Feast Day, Candlemas Day, why so called, i. 138.
Wolsey's (Cardinal) Rudimenta Grammatices, notice of, i. 26.
Women, employments and dress of the younger part of, in
Shakspeare's time, i. 83, 84.
Characters of women, personated by men and boys, 221.
Wood (Nathaniel), a dramatic writer in the reign of Elizabeth,
notice of, ii. 238.
Wool-trade, allusions to, i. 35.
Promoted by Queen Elizabeth, 192. note.
"World's Folly," a collection of old ballads, notice of, i. 474-476.
Wotton (Sir Henry), encomium of, on angling, i. 297.
Character of his poetical productions, 672, 673.
Wright (John), character of his "Passions of the Minde," a
collection of essays, i. 511.
Wright (Leonard), character of his "Display of Dutie," i. 512,
513.
Wriothesly (Thomas), Earl of Southampton, biographical notice
of, ii. 1, 2.
A passionate lover of the drama, 2.
Shakspeare's Venus and Adonis, and Rape of Lucrece,
dedicated to him, 3.
His liberality to the poet, 4.
Joins the expedition to the Azores, 5.
In disgrace with Queen Elizabeth, 6.
Goes to Paris, and is introduced to King Henry IV., 7.
Marries Elizabeth Vernon without consulting the Queen, 7, 8.
Who imprisons them both, 8.
Goes to Ireland with the Earl of Essex, who promotes him,
ibid.
Is recalled and disgraced, 8, 9.
Quarrels with Lord Gray, 9, 10.
Joins Essex in his conspiracy against the Queen, 10.
And is sentenced to imprisonment, ibid.
Released by James I., 11.
Who promotes him, 12, 13.
Birth of his son, 12.
Embarks in a colonising speculation, 13.
Patronises literature, 14.
Opposes the court, 15.
Dies in Holland, 16.
Review of his character, ibid.
Tributes to his memory by the poets and literary men of his
time, 17-19.
Shakspeare's sonnets principally addressed to him, 62-73.
Wyat (Sir Thomas), character of his sonnets, ii. 53.
Wyrley (William), notice of the biographical poems of, i. 707.

Y
Yates (James), "Castle of Courtesie," i. 707.
Yeomen. See Farmers.
Yong (Bartholomew), notice of his "Version of Montemayer's
Romance of Diana," i. 707. and note [707:C].
Yule-clog, or Christmas-block, i. 194.

Z
Zouche (Richard), notice of his "Dove," a geographical poem, i.
707.

THE END.
Printed by A. Strahan,
Printers-Street, London.
THE FOLLOWING WORKS
MAY ALSO BE HAD OF
T. CADELL AND W. DAVIES, STRAND.

1. THE PLAYS OF WILLIAM SHAKSPEARE, in 21


Volumes 8vo.; with the Corrections and Illustrations of various
Commentators. To which are added, Notes by Samuel Johnson and
George Steevens, revised and augmented by Isaac Reed; with a
Glossarial Index. The sixth Edition, Price 12l. 12s. in Boards, or in
Royal Octavo, Price 18l. 18s. in Boards.

2. THE PLAYS OF WILLIAM SHAKSPEARE, accurately


printed from the Text of the corrected Copy left by the late George
Steevens, Esq.: with a series of Engravings from the original Designs
of Henry Fuseli, Esq. Professor of Painting; and a Selection of
Explanatory and Historical Notes, from the most eminent
Commentators; a History of the Stage, a Life of Shakspeare, &c. By
Alexander Chalmers, A.M. A new Edition, in Nine Volumes, 8vo. Fine
Paper, Price 5l. 8s. in Boards. Without the Plates, 4l. 14s. 6d. in
Boards. On Common Paper, without the Plates, 3l. 12s. in Boards.

3. THE WORKS OF BEN JONSON, in Nine Volumes 8vo.;


with Notes Critical and Explanatory, and a Biographical Memoir. By
W. Gifford, Esq. Price 6l. 6s. in Boards, or in Royal 8vo. Price 9l. in
Boards.
4. THE PLAYS OF PHILIP MASSINGER, in Four Volumes
8vo.; with Notes Critical and Explanatory, by W. Gifford, Esq. Price:
2l. 12s. in Boards, or in Royal 8vo. Price 4l. 4s. in Boards.

5. THE WORKS OF THOMAS OTWAY, in Two Volumes


8vo., with a Portrait of the Author. Consisting of his Plays, Poems,
and Letters, with a Sketch of his Life, enlarged from that written by
Dr. Johnson. Price 1l. 4s. in Boards.

6. THREE PLAYS, with a PREFACE; including Dramatic


Observations of the late Lieut.-General Burgoyne. By William Hayley,
Esq. Elegantly printed in 8vo. Price 9s. in Boards.

POEMS and PLAYS, by the same Author, in Six Volumes, Small


8vo. Price 18s. in Boards.

7. BIOGRAPHICA DRAMATICA, or a Companion to the


Playhouse; containing Historical and Critical Memoirs and original
Anecdotes of British and Irish Dramatic Writers, from the
Commencement of our Theatrical Exhibitions; among whom are
some of the most celebrated Actors. Also an Alphabetical Account
and Chronological Lists of their Works, the Dates when printed, and
Observations on their merits, together with an introductory View of
the Rise and Progress of the British Stage. Originally compiled to the
Year 1764 by David Erskine Baker, continued thence to 1782 by
Isaac Reed, F.A.S., and brought down to the End of 1811, with very
considerable Additions and Improvements throughout, by Stephen
Jones. In 4 Volumes 8vo. Price 2l. 8s. in Boards.

8. THE WORKS OF WILLIAM MASON, M. A., Precentor


of York, and Rector of Aston; consisting of The English Garden, a
Poem; the Dramatic Poems of Elfrida and Charactacus;
Miscellaneous Poems; Translation of Du Fresnoy's Art of Painting,
with Notes by Sir Joshua Reynolds; Sermons, &c. Published under
the direction of his Executors. Elegantly printed in Four Volumes,
8vo., with Portraits of Mr. Mason, Lord Holdernesse, and Dr. Burgh,
from original Pictures. Price 2l. 2s. in Boards.

9.THE WORKS OF THE RIGHT HON. JOSEPH


ADDISON, with Notes by the late Richard Hurd, D.D., Lord Bishop
of Worcester. Elegantly printed in Six Volumes 8vo., and illustrated
with a Portrait of Mr. Addison, from an original Picture by Dahl. Price
3l. 12s. in Boards, or in Royal 8vo., Price 5l. 8s. in Boards.

10. ANECDOTES OF DISTINGUISHED PERSONS,


chiefly of the last and Two preceding Centuries. Illustrated by
Engravings. By William Seward. The Fifth Edition, in Four Volumes
8vo. Price 1l. 16s. in Boards.

11. THE WORKS OF THE ENGLISH POETS, from


Chaucer to Cowper; including the Series edited, with Prefaces,
Biographical and Critical, by Dr. Samuel Johnson: and the most
approved Translations. The additional Lives by Alexander Chalmers,
Esq. F.S.A. In 21 Volumes Royal 8vo. Price 25l. in Boards.

12. THE LIVES OF THE ENGLISH POETS, with Critical


Observations on their Works. In Three Volumes 8vo. Price 1l. 4s. in
Boards, or in Three Pocket Volumes, Price 12s. in Boards.

The Reader is requested to correct the three following ERRATA in the


Index.
Vol. II. page 644. col. 1. line 32. For "As You Like It,"
read "Merry Wives of Windsor."
—— page 667. col. 1. line 52. For "and probably also,"
read "but not."
—— page 676. col. 2. line 46. The following passage,
as referring to our great Epic Poet, should have been
placed under the article Milton instead of Wotton:
—"Whether he and Shakspeare were acquainted with
each other."

TRANSCRIBER'S NOTES:
Pages vi and 626 are blank in the original.
Page numbers 332 and 333 are not used in the
original. A comparison with other editions of the
book shows that no text is missing. Page numbers
337 and 338 were used twice. The numbers have
been changed to 337a, 338a, 337b, and 338b.
There are two pages numbered 354 and no page
numbered 352. The first page 354 has been
renumbered to 352.
Corrections listed in the Errata have been
made.
In the Index, symbolic references to footnotes
have been replaced with the correct footnote
designation.
On page 223, there was a large white space
inside parentheses. The white space has been
replaced by four dashes.
If the images are not visible on page 519, the
first two are the symbol for Jupiter , and the
third is the symbol for Venus .

The following corrections have been made to


the text:
Page iv: the page reference for CHAP.
IX was changed from 258 to 256.
Page 26: Whose ridges with the
meeting clouds contend."[quotation mark
missing in original]
Page 27: As mountain snow melts with
the mid-day sun."[quotation mark missing
in original]
Page 36: "Of skilful painting, made for
Priam's Troy,"[quotation mark missing in
original]
Page 59: "W. H.,"[quotation mark
missing in original] he continues
Page 66: virtuous wish would bear you
living flowers."[quotation mark missing in
original]
Page 67: That due of many now is thine
alone:"[quotation mark missing in original]
Page 68: The very part was consecrate
to thee."[quotation mark missing in
original]
Page 69: That every word doth almost
tell my name."[quotation mark missing in
original]
Page 74: Pomfret and——but[original
has "and ——, but"] the name
Page 87: by and by the Turkish[original
has "Turkisk"] maner is generallie best
liked
Page 106: Had falsely thrust upon
contrary feet:"[quotation mark missing in
original]
Page 111: That, rifling thee, have rob'd
at least a score.""[quotation mark missing
in original]
Page 117: all night like a watching-
candle?"[quotation mark missing in
original]
Page 119: would often shew to his
friends.'"[single quote missing in original]
Page 131: [original has extraneous
quotation mark]to speak first of the
election of sweet wines
Page 139: 8. "Item, [original has
extraneous quotation mark]That no man
waite at the table
Page 145: defray all the chardges for
me."[quotation mark missing in original]
Page 149: "[quotation mark is missing
in original]he did never come to deliver
any
Page 161: "[quotation mark missing in
original]O, how blessed do I take mine
eyes
Page 163: lxx or lxxx[original has "Ixx
or Ixxx"] poore men marchinge
Page 165: his dagge w{th} II.[original
has "11"] bulletts
Page 168: with Masks, Shews,
Fireworks, &c."[quotation mark missing in
original]
Page 168: triumphes, cresset
lights[original has "triumphes cresset,
lights"]
Page 184: worthless class of the
nineteenth century:[original has
extraneous quotation mark]
Page 194: who tells us, that "[quotation
mark missing in original]she was twelve
times at Theobald's
Page 211: commoner, buying his sport
by the penny."[quotation mark missing in
original]
Page 229: tragi-comedy became
necessary to[original has "so"] catch their
applause
Page 240: "[quotation mark missing in
original]Bethsabe. Come gentle Zephyr
Page 246: Still gushing."[quotation
mark missing in original]
Page 247: horror, is the chef
d'œuvre[original has "d'æuvre"] of
Marlowe
Page 257: Aubrey[original has
"Aubery"] tells us
Page 258: and moral integrity[original
has "in-integrity" split across a line break]
of Shakspeare
Page 271: Such strong renown as time
shall never—"[quotation mark missing in
original]
Page 274: Per. ——————— [original
has extraneous quotation mark]I embrace
you, sir.
Page 276: Whirring me from my
friends;"[quotation mark missing in
original]
Page 279: Waste it for you, like taper-
light."[quotation mark missing in original]
Page 288: be confessed that the
doggrel[original has "droggrel"] verses
Page 303: in the superhuman
mistresses[original has "misioesses"]
Page 328: the nurse, when, for her
lovely child,[original has a period]
Page 334: cried the one, 'an it's a'
done!'[original has a double quote]
Page 339: And bless it to all fair
posterity;"[quotation mark missing in
original]
Page 347: With juice of balm, and
every precious flower."[quotation mark
missing in original]
Page 350: "[quotation mark missing in
original]Cum—inter ambiguas noctis
Page 350: do continually tary in the
house;"[quotation mark missing in
original]
Page 368: it abounds with γνωμαι;
[original has "γνομαι" without a semi-
colon]
Page 373: envious, and
hypocritical[original has "hyprocritical"] in
his disposition
Page 379: because they are too long to
be one[379:B],"[quotation mark missing in
original]
Page 379: to which he, and his
immediate[original has "immeditate"]
successor
Page 384: spirited[original has
"spririted"] and glowing sketches of
Bardolph
Page 402: the living, and[original has
"and and"] that they
Page 403: till they shall have
undergone a similar refinement."
[quotation mark missing in original]
Page 411: The bell then beating
one:"——[quotation mark missing in
original]
Page 421: K. Phi. You are as fond of
grief, as of your child.[original has a
comma]
Page 423: For the contempt of empire,"
[quotation mark missing in original]
Page 437: 22.["22." missing in original]
Troilus and Cressida: 1601.
Page 443: May here find truth too."
[quotation mark missing in original]
Page 479: diseases that vex[original
has "ver"] them strangelie
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!

ebookball.com

You might also like