0% found this document useful (0 votes)
8 views

Javascript Data Structures And Algorithms An Introduction To Understanding And Implementing Core Data Structure And Algorithm Fundamentals 1st Edition Sammie Bae pdf download

The document is about the book 'JavaScript Data Structures and Algorithms' by Sammie Bae, which introduces core data structure and algorithm fundamentals. It includes various chapters covering topics such as Big-O notation, JavaScript unique features, numbers, strings, arrays, objects, memory management, and recursion. The book is available for download and is aimed at helping readers understand and implement these concepts in JavaScript.

Uploaded by

hristiabire
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
0% found this document useful (0 votes)
8 views

Javascript Data Structures And Algorithms An Introduction To Understanding And Implementing Core Data Structure And Algorithm Fundamentals 1st Edition Sammie Bae pdf download

The document is about the book 'JavaScript Data Structures and Algorithms' by Sammie Bae, which introduces core data structure and algorithm fundamentals. It includes various chapters covering topics such as Big-O notation, JavaScript unique features, numbers, strings, arrays, objects, memory management, and recursion. The book is available for download and is aimed at helping readers understand and implement these concepts in JavaScript.

Uploaded by

hristiabire
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/ 83

Javascript Data Structures And Algorithms An

Introduction To Understanding And Implementing


Core Data Structure And Algorithm Fundamentals
1st Edition Sammie Bae download
https://ebookbell.com/product/javascript-data-structures-and-
algorithms-an-introduction-to-understanding-and-implementing-
core-data-structure-and-algorithm-fundamentals-1st-edition-
sammie-bae-52953836

Explore and download more ebooks at ebookbell.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Javascript Data Structures And Algorithms An Introduction To


Understanding And Implementing Core Data Structure And Algorithm
Fundamentals Paperback Sammie Bae

https://ebookbell.com/product/javascript-data-structures-and-
algorithms-an-introduction-to-understanding-and-implementing-core-
data-structure-and-algorithm-fundamentals-paperback-sammie-bae-7435288

Learning Javascript Data Structures And Algorithms Second Edition


Loiane Groner

https://ebookbell.com/product/learning-javascript-data-structures-and-
algorithms-second-edition-loiane-groner-21953118

Learning Javascript Data Structures And Algorithms Write Complex And


Powerful Javascript Code Using The Latest Ecmascript 3rd Edition
Loiane Groner

https://ebookbell.com/product/learning-javascript-data-structures-and-
algorithms-write-complex-and-powerful-javascript-code-using-the-
latest-ecmascript-3rd-edition-loiane-groner-42304908

Learning Javascript Data Structures And Algorithms 3rd Edition Loiane


Groner

https://ebookbell.com/product/learning-javascript-data-structures-and-
algorithms-3rd-edition-loiane-groner-7113186
Learning Javascript Data Structures And Algorithms Second Edition 2nd
Edition Loiane Groner

https://ebookbell.com/product/learning-javascript-data-structures-and-
algorithms-second-edition-2nd-edition-loiane-groner-48320106

Learning Javascript Data Structures And Algorithms 4th Edition Early


Access 4th Loiane Groner

https://ebookbell.com/product/learning-javascript-data-structures-and-
algorithms-4th-edition-early-access-4th-loiane-groner-59431510

Learning Javascript Data Structures And Algorithms Second Edition


Loiane Groner

https://ebookbell.com/product/learning-javascript-data-structures-and-
algorithms-second-edition-loiane-groner-42038434

Learning Javascript Data Structures And Algorithms Second Edition


Groner

https://ebookbell.com/product/learning-javascript-data-structures-and-
algorithms-second-edition-groner-35900432

Learning Javascript Data Structures And Algorithms Second Edition


Loiane Groner

https://ebookbell.com/product/learning-javascript-data-structures-and-
algorithms-second-edition-loiane-groner-37301048
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
Random documents with unrelated
content Scribd suggests to you:
Tan pura y transparente
Es creación viviente
De incógnito poder.

Mirábala embebido
El Nazarita príncipe,
Cuando llegó á su oído
La deliciosa voz
Que oyó de la caverna
En la extensión interna
Sonar, cuando detúvose
Su palafrén veloz.

Y la escondida música
Que en torno de él resuena
De júbilo le llena,
Le embriaga el corazón,
Y la palabra mística
De aquel cantar de gloria
Le trae á la memoria
Antigua aparición.

Dibújase en su mente
Un valle de Granada
Con una fresca fuente
De lánguido rumor,
En una perfumada
Noche, sin nube alguna
El Cielo, de la luna
Plateada al resplandor.

Y cuanto más escucha


Su armónico concierto,
Un rumbo va más cierto
Un rumbo va más cierto
Tomando el corazón.
Triunfante de la lucha
Con la ilusión pasada
Del valle de Granada,
Al comprender su són.

—«Salud ¡oh Nazarita!


Bien llegues á las nieblas
Cuya región habita
Tu genio protector.
Ha visto en las tinieblas
Resplandecer tus ojos:
Te conoció, y de hinojos
Dió gracias al Señor.

»Su vista rutilante,


Que el universo abarca,
Posada en tu semblante
Desde tu cuna está,
Y el dedo omnipotente
Sobre tu noble frente
Grabó la regia marca,
Que á conocer te da.

»Naciste favorito
Del genio y de la gloria:
Tu nombre fué victoria,
Tu voluntad ley fué.
Tu tiempo es infinito,
Profundas son tus huellas,
Propicias las estrellas
Son á Nazar: ten fe.
»Avanza, Nazarita;
Radiante aquí tu estrella
Con viva luz destella,
Aquí en tu Alhambra estás:
Aquí mana infinita
La fuente del consuelo.
Avanza, aquí del cielo
Más cerca reinarás.»

De la celeste música
La letra así decía,
Y, atento á su armonía,
El príncipe Al-hamar
Permanecía atónito
Sin voz ni movimiento,
En dulce arrobamiento
Gozando sin cesar.

El agua, de que llena


La alberca está, ondulante
Refleja cada instante,
Más vario resplandor,
Cual si una luz serena
Bajo la linfa clara
Recóndita radiara
Con trémulo fulgor.

Debajo de su planta
Percibe que el divino
Concierto se levanta,
Del manantial detrás,
Y al borde cristalino
De la colmada alborea,
Que está á sus pies, se acerca
Que está á sus p es, se ace ca
Cada momento más.

Y he aquí que en este punto


Del fondo transparente
Del agua donde siente
La música sonar.
De un sér resplandeciente
El rostro, que ilumina
La linfa cristalina,
Se comenzó á elevar.

Tocó en el haz del agua


Su cabellera blonda:
Quebró la frágil onda
Su frente virginal:
Dejó el agua mil hebras
Entre sus rizos rotas,
Y á unirse volvió en gotas
Al limpio manantial.

Aéreo, puro, leve,


Cual nube vaporosa
Que mansa el aura mueve
Y transparenta el sol,
Ciñendo de oro y rosa
Flotante vestidura,
Como el del alba pura
Suavísimo arrebol:

La paz en el semblante,
La gloria en la sonrisa,
Apareció radiante
El ángel Azäel;
Y sus mortales ojos
Fijando en la improvisa
Aparición, de hinojos
Cayó Al-hamar ante él.

Del agua se alzó fuera


Y, al esparcir el viento
Su blonda cabellera,
El aire perfumó:
Dejó escapar su aliento,
Y cuanto allí existía
Su aliento de ambrosía
Con ansia respiró.

Del suelo á la techumbre


El místico palacio
Reverberó la lumbre
De su divina faz,
Cuya fulgente aureola
Purpúrea tornasola
El aire del espacio
Y de las aguas la haz.

Y he aquí que su alba mano


El ángel extendiendo
Y alzando y atrayendo
Al príncipe hacia sí,
Con plácida sonrisa
Y acento soberano,
Que armonizó la brisa
Fragante, hablóle así:

«Yo visité en un sueño


Tu espíritu en la tierra
Tu espíritu en la tierra,
Mostrándote halagüeño
Tu porvenir en él.
Tesoros te di y gloria,
Tu esclava hice á la guerra,
Grabando en tu memoria
La imagen de Azäel.

»Iluminé tu ciencia,
Colmé de sabios planes
Tu humana inteligencia
Y al logro te ayudé.
Cual tu ambición lo quiso
Cumpliendo tus afanes,
Terreno paraíso
Tu rico imperio fué.

»Yo inoculé en tu alma


El germen de la duda
Para turbar la calma
De tu crëencia vil:
Para que espuela fuera
Con cuya lenta ayuda
Á la verdad se abriera
Tu corazón gentil.

»Brotar hice en tu suelo


Para calmar tus penas
Las aguas del consuelo,
Que á conocer te di:
Mas de tristeza llenas
Cien noches has pasado,
Y al agua no has llegado
Cuyo raudal te abrí.
»Al verte victorioso,
Temido y opulento,
Tu corazón atento
Sólo á la tierra fué.
Dudaste, mas dudando
No osaste perezoso
El rostro á mí tornando
Poner en mí tu fe.

»Y hacia el fatal destino


Á que traidora guía
La falsa fe, te vía
Adelantar Luzbel:
Y el fin de tu camino
Mostrándome decía:
Caer era su sino:
Le pierdes, Azäel.

»Lloraba yo abismado
En mi amargura, viendo
Mi afán tan malogrado,
Tan sin valor mi fe:
Y, en mi pesar y enojo
Postrer esfuerzo haciendo,
Con temerario arrojo
Entre ambos me lancé.

»Luchamos: el Eterno,
De mi dolor movido,
Caer dejó en su oído
Su nombre y dió á mis pies.
Sumíle en el infierno:
Y en alas de un nublado
e a as de u ub ado
Te traje arrebatado
Adonde en paz te ves.

»Los pérfidos espíritus


Que en pos de ti traías,
Las vanas fantasías
De tu crëencia ruin
Mostrábante. ¡Quiméricos
Esfuerzos! ¡Sueños breves!
Aullando, de mis nieves
Se quedan al confín.

»Mas ¡ay! yo te conquisto


Los cielos..... y ¡cuán caro
Me cuesta á mí el amparo
Que liberal te doy!
Dos siglos ha que existo
Aquí, expiando un yerro,
Y añado á mi destierro
Uno, por ti, más hoy.

»Á condición tan dura


Tu salvación compraba,
Nazar; mas yo te amaba
Tanto, que la acepté;
No supe resignarme
Á arrebatar dejarme
Tan noble criatura,
Y tu alma rescaté.

»¡Oh! juzga bien en cuánto


Me es cara tu alma buena,
Cuando á mi larga pena
í
Cien soles añadí
Por ella. Ahora el santo
Fallo, inmutable, extremo,
Oye que el Juez Supremo
Fulmina contra ti.

»Hoy mismo, en apariencia,


Perecerá á las manos
De incógnita dolencia
Tu cuerpo terrenal:
Más junto á mí existencia
Tendrás, hasta que ufanos
Habiten los cristianos
Tu alcázar oriental.

»Yo les haré á Granada


Cercar como un enjambre:
Con ellos vendrá el hambre,
La muerte y el baldón:
Y talarán tus tierras,
Y en sanguinarias guerras
Tu raza aniquilada
Será sin compasión.

»Tú lo verás: estrella


Fatal para tu gente,
Tú verterás sobre ella
Roja, siniestra luz:
Y lidiarás conmigo
En pro del enemigo,
Sobre el pendón de Oriente
Hasta clavar la Cruz.

»Ahogado el Islamismo
»Ahogado el Islamismo
Y desbandada y rota
Tu raza, gota á gota
Su sangre en ti caerá:
Su sangre es tu bautismo,
Y este de afán y duelos
Misterio, de los Cielos
Las puertas te abrirá.

»No hay más que un Dios. Justicia


En Él no más se encierra.
Tu empresa fué en la tierra
Dios sólo es vencedor:
Por eso te es propicia:
Mas nadie entra en su gloria
Sin pena expiatoria
Hasta del leve error.

»Tal es nuestra sentencia:


Tal es el purgatorio
Que la alta Providencia
Nos señaló á los dos.
Obra de nuestras manos,
En dón propiciatorio
Se han de ofrecer, cristianos,
Un Rey y un pueblo á Dios.

»Tú el Rey: el pueblo el tuyo.


Tan sólo dignamente
Así me restituyo
Al Cielo, que dejé.
Apróntate obediente
Á dividir conmigo
La gloria y el castigo
Que para ti acepté
Que para ti acepté.

»¡Sús, pues, oh Nazarita!


De Dios al pie del trono,
Rogándole en tu abono,
Le respondí de ti.
¡Sús, pues! Á la bendita
Empresa apresta el brío;
Mortal, te hice igual mío;
Sé digno tú de mí.»

Dijo Azäel: estático


Á su divino acento,
Embebecido, atento,
Estúvose Al-hamar:
Cedió su noble espíritu
Al celestial destino,
Y se empezó el divino
Misterio á efectuar.

«Mira,» le dijo entonces


El ángel desterrado:
Y (hacia el lugar tornado
Que el ángel señaló)
El muro en dos partido,
Sobre invisibles gonces
Girando dividido,
El Nazarita vió.

Se abrió sobre un espejo


En cuyo misterioso
Cristal, con el reflejo
De un matinal albor,
Se alumbra una campiña,
Se a u b a u a ca p a,
Que Mayo lujurioso
Con su fecundo aliña
Primaveral verdor.

Una ciudad, fundada


Al pie de una alta sierra,
Domina aquella tierra
Por donde arroyos mil
Serpean: es Granada,
Su vega, sus alturas
Y las corrientes puras
De Darro y de Genil.

Espléndida cohorte
De Moros atraviesa
Por su alameda espesa
Llevando un ataúd,
Y á la muralla corva
De la morisca corte
Se agolpa á verles torva
Callada multitud.

Llegáronse á la puerta
De Elvira aquellos fieles
Muslimes; allí abierta
La turba les dejó
Paso, y subiendo á espacio
La cuesta de Gomeles,
Entrada en el palacio
Bib-el-Leujar les dió.

La multitud atenta
Y silenciosa iba
En pos su marcha lenta
Siguiendo: y, al tocar
La puerta judiciaria,
La triste comitiva
Paróse voluntaria
Dejándose cercar.

Entonces, elevando
El ataúd en hombros
Los que le van llevando,
Y puesto junto á él
Un Alfakí, inspirando
Doquier pavor y asombros,
«¡Llorad!—(dijo él llorando)
»Con lágrimas de hiel.

»¡Llorad toda la vida,


»¡Oh huérfanos Muslimes!
»¡La flor de los alimes,
»¡La palma de Nazar,
»¡La gloria del Oriente,
»Cayó del rayo herida!
»¡Llorad eternamente,
»Llorad sobre Al-hamar!»

Así con ronco acento


El Alfakí clamando,
Del ataúd alzando
El paño funeral,
Al pueblo los despojos
Del rey mostró; y al viento
El pueblo, al caer de hinojos,
Dió un ¡ay! universal.
Á este eco de agonía,
Que atravesó perdido
El aire hasta su oído,
Se estremeció Al-hamar.
Quitóse del espejo
Do escena tal veía,
Y se tornó el reflejo
Del vidrio á disipar.

«¡Ea!—Azäel le dijo—
»Monarca de la tierra,
»El ataúd encierra
»Tu polvo terrenal;
»Mas, de los cielos hijo,
»Del ataúd te exhalas.
»Desplega, pues, tus alas,
»Espíritu inmortal.»

Entonces el rey árabe


Sintióse aéreo, leve,
Cual luz que el aire mueve,
Cual nube que va en él.
Sólo era ya un espíritu,
Una visión ligera,
Un alma compañera
Del Ángel Azäel.

El silencioso vuelo
Ambos á dos alzando,
En el azul del cielo
Perdiéronse los dos;
Y, entre sus auras leves
Su rastro abandonando,
El libro de las nieves
El libro de las nieves
Concluye. ¡Gloria á Dios!
EPÍLOGO
¡Gloria á Dios!—De Al-hamar el Granadino
Así la historia celestial concluye;
Llámala el Musulmán cuento divino,
Y en libros su relato distribuye.
Su sacra inspiración del Cielo vino
Y al Cielo desde aquí se restituye;
Tradición oriental, es la portada
Del oriental poema de Granada.

Cual dos cisnes que, al par atravesando


El mar azul con encontrado vuelo,
Isla apartada en su extensión hallando
En ella toman anhelado suelo,
Reposan juntos, y á partir tornando
Tornan la anchura á dividir del cielo,
Y de su voz un punto los sonidos
Se elevan en el aire confundidos:

Como dos peregrinos que una tienda


Dividen del desierto en la desnuda
Soledad, de Al-hamar en la leyenda
Dos poetas ocúltanse sin duda.
Uno á Aláh en sus cantares se encomienda,
Otro al Dios de la Cruz demanda ayuda.
¿Quién no percibe en ella confundidos
Brotar de sus dos arpas los sonidos?

Dióles á ambos el Genio soberano


La misma inspiración, el mismo aliento:
Mas pasando tal vez de una á otra mano
De uno y otro el armónico instrumento,
El Árabe poeta y el Cristiano
Sacan de él á la par distinto acento,
í
Exhalando mezclada su armonía
La Árabe y la Cristiana poesía.

Confundidos así sus dos cantares


Entonan á una voz los dos cantores,
Y de la Cruz divina los altares
El poeta oriental orna con flores
Que tejen las hurís sus tutelares;
Pero de un solo SÉR adoradores,
«No hay más que un solo Dios»—dice el Cristiano;
«No hay más Dios sino Dios»—el Africano.

Tal es la historia peregrina y bella


Que os dan sobre estas hojas extendida.
Lëedla sin temor: nada hay en ella
Que la razón rechace, ó la fe impida;
La luz que de sus páginas destella
Despierta el alma á la virtud dormida,
Y eleva el corazón y el pensamiento
Á la pura región del firmamento.

Lëedla pues: y el ámbar que perfuma


Del paraíso la mansión divina,
Y el resplandor que de la Esencia suma
Derramado los mundos ilumina,
Y el rumor que levantan con su pluma
Las alas de Gabriel cuando camina,
Embalsame y alumbre y dé contento
Á cuantos lean el divino cuento.

FIN DE LA LEYENDA DE AL-HAMAR.


GRANADA
POEMA ORIENTAL

Cristiano y español, con fe y sin miedo,


Canto mi religión, mi patria canto.
LIBRO PRIMERO

EXPOSICIÓN

INVOCACIÓN
En el nombre de Dios omnipotente,
Cuya presencia el universo llena,
Cuya mirada brilla en el Oriente,
Nutre las plantas y la mar serena,
Canto la guerra en que la hispana gente
Al África arrojando á la agarena,
Selló triunfante con la Cruz divina
Las torres de la Alhambra granadina.

¡Espíritu de Dios único y trino,


Ángel Custodio de la Fe Cristiana,
Único fuego que del Cielo vino,
Única fuente que incorrupta mana,
Único rayo del fulgor divino,
Única inspiración que soberana
Eleva al Criador la poesía:
Yo invoco tu favor para la mía!

Sostén mi voz, mi espíritu aconseja:


Mas tolera que en carmen Africano
Recoja alguna flor con que entreteja
Cairel morisco á mi laúd cristiano:
Ni juzgues que mi fe de Ti se aleja,
Si algunas veces del harén profano
Las alkatifas perfumadas piso,
Ó invoco á las hurís del paraíso.

Voy la gloria á cantar de dos naciones


Por religión é instintos enemigas,
Que, fieles á la par á sus pendones,
Prodigaron al par sangre y fatigas,
Rojas brotar haciendo sus legiones
Con la sangre común aguas y espigas:
ó
Y cual la de los dos corrió mezclada,
Junta debe su gloria ser cantada.

Pues no porque en su límpida entereza


Conserve yo la fe de los Cristianos
Que hicieron del desierto á la aspereza
Volver á los vencidos Africanos,
Del vencedor loando la grandeza
Trataré á los vencidos de villanos.
No: siete siglos de su prez testigos
Los dan por caballeros si enemigos.

Lejos de mí tan sórdida mancilla:


Antes selle mi boca una mordaza
Que llame yo en la lengua de Castilla
Á su raza oriental bárbara raza.
Jamás: aún en nuestro suelo brilla
De su fecundo pie la extensa traza,
¡Y, honrado y noble aún, su sangre encierra
Más de un buen corazón de nuestra tierra!

¡Augusta sombra de Isabel! perdona


Si mi ruda canción osa atrevida,
Llegando irreverente á tu persona,
Del féretro evocarte á nueva vida.
Sé que la gloria que inmortal te abona
No puede por mi voz enaltecida
Ser: mas yo bajo á tu mansión mortuoria
No á engrandecer, sino á adorar tu gloria.

Díselo así al Católico Fernando,


Si en medio de las dichas celestiales
Alguna vez, por el Edén vagando,
Recordáis vuestras glorias terrenales
Recordáis vuestras glorias terrenales,
La obscura tierra desde el sol mirando:
Y al escuchar mis cánticos mortales,
Mirad á vuestra gloria, que me inspira,
No al rudo canto de mi tosca lira.

Y vosotros, guerreros de Castilla,


Honor de sus más ínclitos solares,
Nobles Condes de Cabra y de Tendilla,
Merlos, Téllez, Girones y Aguilares,
Cárdenas y Manriques de Sevilla,
Fieles Vargas, intrépidos Pulgares,
Córdovas generosos de Lucena,
Impávidos Clavijos de Baena:

Mendozas de alta prez, Portocarreros


Y Ponces de León, de cuya historia
Sus anales jamás perecederos
Henchidos guarda la Española gloria:
Y vosotros también, ¡oh caballeros
Árabes! dignos de gentil memoria:
Muza, postrero campeador del Darro,
Indeciso Boabdil, Zagal bizarro,

Aly-Athar insepulto, Hamet Rondeño,


Lince de las fronteras castellanas,
Reduán inalterable y zahareño,
Gazul de las doncellas africanas
Querido, Hacén tenaz, Ozmín trigueño,
Tarfe, horror de las crónicas cristianas;
Y vosotras, sultanas granadinas
De nombres y leyendas peregrinas:

Aija la varonil, matrona osada


ja a a o , at o a osada
Jamás rendida á su fatal destino:
Zoraya, la cautiva renegada,
Por cuyos hijos la discordia vino
Á derribar el trono de Granada:
Moraima la de Loja, á quien su sino
Obligó á encomendar sin esperanza
Vida y honor á Castellana lanza;

Perdonadme también si mis canciones,


Á través de los mármoles tendidos
En vuestros solitarios pantëones,
Hieren en ronco són vuestros oídos.
Sé que merecen más vuestras acciones
Que elogios en mi voz mal atendidos:
Mas si, en fuerzas escaso, á tal me atrevo,
Es porque sé lo que á mi patria debo.

Sé que es la empresa donde me he empeñado


Dédalo obscuro, inmensurable abismo,
Do sólo penetrar han intentado
Necia temeridad ó alto heroísmo:
Conozco que, en mi orgullo, demasiado
Fío en mi corazón, fío en mí mismo:
Mas supera la fe mi atrevimiento,
Y fío en Dios que abonará mi intento.

Deliciosos recuerdos de otros días


De honor y de placer, de amor y gloria,
Que envuelta en romancescas fantasías
Guardáis oculta vuestra bella historia,
Exhalada en confusas armonías
De himnos de amor y gritos de victoria:
Dad á mi corazón, dad á mi aliento
Generoso poder, canoro acento.
Ge e oso pode , ca o o ace to

Águilas que os cernéis con corvo vuelo


Sobre el Atlas y el Cáucaso; pastores
Que sesteáis á la sombra del Carmelo
Y bajáis al Jordán los baladores
Ganados: y vosotros los que en pelo
Montáis salvajes potros voladores,
Hijos de los ardientes vendavales
Que barren los egipcios arenales;

Tribus perdidas y á las de hoy extrañas,


Para quienes la Europa no se ha abierto,
Que incendiáis al huir vuestras cabañas
Y en la Zahara avanzáis el paso incierto;
Gacelas de las árabes montañas,
Apareadas palmas del desierto;
Caravanas errantes á quien ellas
Dátiles dan y leche las camellas;

Palomas de los cármenes floridos


Que bordan las colinas de Granada;
Golondrinas leales que los nidos
En la Alhambra colgáis; enamorada
Raza de ruiseñores que escondidos
Gorjeáis de su bosque en la enramada,
Arroyos que, á su sombra, bullidores,
Laméis su césped y mecéis sus flores;

Sierras que cubre el sempiterno hielo


Donde Darro y Genil beben su vida;
Valles salubres, transparente cielo
De la Alpujarra aún mal conocida;
De Málaga gentil alegre suelo
De la hermosura y del amor guarida;
Mar azul cuyo lomo cristalino
Á las quillas de Agar prestó camino:

Abridme los tesoros encantados


De vuestras glorias mil tradicionales;
Dadme á beber los que guardáis sagrados
De inspiración inmensos manantiales;
Germinad en mi mente, no estudiados,
Vuestros cantos de amor meridionales,
Por que pueda brotar del arpa mía
Vuestra oriental y virgen poesía.

De sus cuerdas despréndanse sonoras


Esas modulaciones nunca oídas
Por los pueblos de Europa, y de las moras
Tribus por nuestros pueblos aprendidas;
Esas notas ardientes, tentadoras,
Que aun hoy por tosca mano repetidas
Renuevan en los huertos de la Alhambra
La de veloz compás morisca zambra.

Venid en torno á mí, generaciones


Ateridas del Norte, que con pieles
Vestís nuestras moriscas tradiciones,
Rasgando sus bordados alquiceles:
Venid á oirlas en sus propios sones
Y lengua original de bocas fieles,
Al pobre són de bárbara guitarra
Debajo de un peñón de la Alpujarra.

Venid, aprenderéis del Mediodía


Cuál el origen es de los cantares
Que jamás comprendió vuestra alma fría;
Que jamás comprendió vuestra alma fría;
Sabréis cómo entre bélicos azares
Nació la abrasadora poesía
De nuestros bellos cantos populares;
Y en el lujo oriental de su riqueza,
Considerad su bárbara grandeza.

Pues por hijos de bárbaros osada


Vuestra historia nos da, sea en buen hora:
No esa bárbara estirpe renegada
Será por mí; mas á admirar ahora
Venid el rastro que dejó en Granada
La ilustración de nuestra estirpe mora:
Y en el lujo oriental de su riqueza
Adorad nuestra bárbara grandeza.

Sí: yo os voy á contar la historia bella


De esos á quien llamáis fieros salvajes,
Y fío en Dios que entenderéis por ella
Que puede despreciar vuestros ultrajes
Quien Alhambras dejó sobre su huella,
Quien labró fortalezas como encajes,
Y quien colmó por cóncavo arrecife
Las albercas del real Generalife.

Yo os voy á hablar del mágico recinto


De esta por ellos habitada tierra,
Y á mostraros lo que este laberinto
De jardines y alcázares encierra.
En llanto y sangre le dejaron tinto,
Pero tan fértil con su amor y guerra,
Que la flor más silvestre aromatiza
Y el más vulgar recuerdo poetiza.
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookbell.com

You might also like