Full Data Structures and Algorithms With JavaScript 1st Edition Michael Mcmillan Ebook All Chapters
Full Data Structures and Algorithms With JavaScript 1st Edition Michael Mcmillan Ebook All Chapters
com
https://ebookname.com/product/data-structures-and-
algorithms-with-javascript-1st-edition-michael-mcmillan/
OR CLICK BUTTON
DOWNLOAD EBOOK
https://ebookname.com/product/data-structures-and-algorithms-
in-c-2nd-edition-michael-t-goodrich/
https://ebookname.com/product/problem-solving-with-algorithms-
and-data-structures-using-python-second-edition-bradley-n-miller/
https://ebookname.com/product/clojure-data-structures-and-
algorithms-cookbook-25-recipes-to-deeply-understand-and-
implement-advanced-algorithms-in-clojure-1st-edition-rafik-
naccache/
https://ebookname.com/product/absolute-beginner-s-guide-to-
ebay-2nd-edition-michael-miller/
Law of electronic commercial transactions contemporary
issues in the EU US and China 1st Edition Faye Fangfei
Wang
https://ebookname.com/product/law-of-electronic-commercial-
transactions-contemporary-issues-in-the-eu-us-and-china-1st-
edition-faye-fangfei-wang/
https://ebookname.com/product/introduction-to-conservation-
genetics-1st-edition-richard-frankham/
https://ebookname.com/product/schizophrenia-cognitive-theory-
research-and-therapy-1st-edition-aaron-t-beck/
https://ebookname.com/product/type-1-diabetes-in-children-
adolescents-and-young-adults-how-to-become-an-expert-on-your-own-
diabetes-2nd-edition-ragnar-hanas/
https://ebookname.com/product/porphyry-against-the-christians-
studies-in-platonism-neoplatonism-and-the-platonic-tradition-
robert-m-berchman/
Hiking Wisconsin Second Edition Kevin Revolinski
https://ebookname.com/product/hiking-wisconsin-second-edition-
kevin-revolinski/
www.it-ebooks.info
www.it-ebooks.info
Data Structures and Algorithms
with JavaScript
Michael McMillan
www.it-ebooks.info
Data Structures and Algorithms with JavaScript
by Michael McMillan
Copyright © 2014 Michael McMillan. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are
also available for most titles (http://my.safaribooksonline.com). For more information, contact our corporate/
institutional sales department: 800-998-9938 or corporate@oreilly.com.
Editors: Brian MacDonald and Meghan Blanchette Cover Designer: Karen Montgomery
Production Editor: Melanie Yarbrough Interior Designer: David Futato
Copyeditor: Becca Freed Illustrators: Rebecca Demarest and Cynthia Clarke
Proofreader: Amanda Kersey Fehrenbach
Indexer: Ellen Troutman-Zaig
Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly
Media, Inc. Data Structures and Algorithms with JavaScript, the image of an amur hedgehog, and related
trade dress are trademarks of O’Reilly Media, Inc.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as
trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a trademark
claim, the designations have been printed in caps or initial caps.
While every precaution has been taken in the preparation of this book, the publisher and authors assume
no responsibility for errors or omissions, or for damages resulting from the use of the information contained
herein.
ISBN: 978-1-449-36493-9
[LSI]
www.it-ebooks.info
Table of Contents
Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix
2. Arrays. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
JavaScript Arrays Defined 13
Using Arrays 13
Creating Arrays 14
Accessing and Writing Array Elements 15
Creating Arrays from Strings 15
Aggregate Array Operations 16
Accessor Functions 17
Searching for a Value 17
String Representations of Arrays 18
Creating New Arrays from Existing Arrays 18
Mutator Functions 19
Adding Elements to an Array 19
Removing Elements from an Array 20
iii
www.it-ebooks.info
Adding and Removing Elements from the Middle of an Array 21
Putting Array Elements in Order 22
Iterator Functions 23
Non–Array-Generating Iterator Functions 23
Iterator Functions That Return a New Array 25
Two-Dimensional and Multidimensional Arrays 27
Creating Two-Dimensional Arrays 27
Processing Two-Dimensional Array Elements 28
Jagged Arrays 30
Arrays of Objects 30
Arrays in Objects 31
Exercises 33
3. Lists. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
A List ADT 35
A List Class Implementation 36
Append: Adding an Element to a List 37
Remove: Removing an Element from a List 37
Find: Finding an Element in a List 38
Length: Determining the Number of Elements in a List 38
toString: Retrieving a List’s Elements 38
Insert: Inserting an Element into a List 39
Clear: Removing All Elements from a List 39
Contains: Determining if a Given Value Is in a List 40
Traversing a List 40
Iterating Through a List 41
A List-Based Application 42
Reading Text Files 42
Using Lists to Manage a Kiosk 43
Exercises 47
4. Stacks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
Stack Operations 49
A Stack Implementation 50
Using the Stack Class 53
Multiple Base Conversions 53
Palindromes 54
Demonstrating Recursion 56
Exercises 57
5. Queues. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
Queue Operations 59
iv | Table of Contents
www.it-ebooks.info
An Array-Based Queue Class Implementation 60
Using the Queue Class: Assigning Partners at a Square Dance 63
Sorting Data with Queues 67
Priority Queues 70
Exercises 72
6. Linked Lists. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
Shortcomings of Arrays 73
Linked Lists Defined 74
An Object-Based Linked List Design 75
The Node Class 75
The Linked List Class 76
Inserting New Nodes 76
Removing Nodes from a Linked List 78
Doubly Linked Lists 81
Circularly Linked Lists 85
Other Linked List Functions 86
Exercises 86
7. Dictionaries. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
The Dictionary Class 89
Auxiliary Functions for the Dictionary Class 91
Adding Sorting to the Dictionary Class 93
Exercises 94
8. Hashing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
An Overview of Hashing 97
A Hash Table Class 98
Choosing a Hash Function 98
A Better Hash Function 101
Hashing Integer Keys 103
Storing and Retrieving Data in a Hash Table 106
Handling Collisions 107
Separate Chaining 107
Linear Probing 109
Exercises 111
9. Sets. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
Fundamental Set Definitions, Operations, and Properties 113
Set Definitions 113
Set Operations 114
The Set Class Implementation 114
Table of Contents | v
www.it-ebooks.info
More Set Operations 116
Exercises 120
vi | Table of Contents
www.it-ebooks.info
The Shellsort Algorithm 171
The Mergesort Algorithm 176
The Quicksort Algorithm 181
Exercises 186
Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
www.it-ebooks.info
www.it-ebooks.info
Preface
Over the past few years, JavaScript has been used more and more as a server-side com‐
puter programming language owing to platforms such as Node.js and SpiderMonkey.
Now that JavaScript programming is moving out of the browser, programmers will find
they need to use many of the tools provided by more conventional languages, such as
C++ and Java. Among these tools are classic data structures such as linked lists, stacks,
queues, and graphs, as well as classic algorithms for sorting and searching data. This
book discusses how to implement these data structures and algorithms for server-side
JavaScript programming.
JavaScript programmers will find this book useful because it discusses how to implement
data structures and algorithms within the constraints that JavaScript places them, such
as arrays that are really objects, overly global variables, and a prototype-based object
system. JavaScript has an unfair reputation as a “bad” programming language, but this
book demonstrates how you can use JavaScript to develop efficient and effective data
structures and algorithms using the language’s “good parts.”
ix
www.it-ebooks.info
For many programmers who didn’t study computer science in school, the only data
structure they are familiar with is the array. Arrays are great for some problems, but for
many complex problems, they are simply not sophisticated enough. Most experienced
programmers will admit that for many programming problems, once they come up with
the proper data structure, the algorithms needed to solve the problem are easier to design
and implement.
An example of a data structure that leads to efficient algorithms is the binary search tree
(BST). A binary search tree is designed so that it is easy to find the minimum and
maximum values of a set of data, yielding an algorithm that is more efficient than the
best search algorithms available. Programmers unfamiliar with BSTs will instead prob‐
ably use a simpler data structure that ends up being less efficient.
Studying algorithms is important because there is always more than one algorithm that
can be used to solve a problem, and knowing which ones are the most efficient is im‐
portant for the productive programmer. For example, there are at least six or seven ways
to sort a list of data, but knowing that the Quicksort algorithm is more efficient than
the selection sort algorithm will lead to a much more efficient sorting process. Or that
it’s fairly easy to implement a sequential or linear search algorithm for a list of data, but
knowing that the binary sort algorithm can sometimes be twice as efficient as the se‐
quential search will lead to a better program.
The comprehensive study of data structures and algorithms teaches you not only which
data structures and which algorithms are the most efficient, but you also learn how to
decide which data structures and which algorithms are the most appropriate for the
problem at hand. There will often be trade-offs involved when writing a program, es‐
pecially in the JavaScript environment, and knowing the ins and outs of the various data
structures and algorithms covered in this book will help you make the proper decision
for any particular programming problem you are trying to solve.
x | Preface
www.it-ebooks.info
Organization of the Book
• Chapter 1 presents an overview of the JavaScript language, or at least the features
of the JavaScript language used in this book. This chapter also demonstrates through
use the programming style used throughout the other chapters.
• Chapter 2 discusses the most common data structure in computer programming:
the array, which is native to JavaScript.
• Chapter 3 introduces the first implemented data structure: the list.
• Chapter 4 covers the stack data structure. Stacks are used throughout computer
science in both compiler and operating system implementations.
• Chapter 5 discusses queue data structures. Queues are an abstraction of the lines
you stand in at a bank or the grocery store. Queues are used extensively in simulation
software where data has to be lined up before it is processed.
• Chapter 6 covers Linked lists. A linked list is a modification of the list data structure,
where each element is a separate object linked to the objects on either side of it.
Linked lists are efficient when you need to perform multiple insertions and dele‐
tions in your program.
• Chapter 7 demonstrates how to build and use dictionaries, which are data structures
that store data as key-value pairs.
• One way to implement a dictionary is to use a hash table, and Chapter 8 discusses
how to build hash tables and the hash algorithms that are used to store data in the
table.
• Chapter 9 covers the set data structure. Sets are often not covered in data structure
books, but they can be useful for storing data that is not supposed to have duplicates
in the data set.
• Binary trees and binary search trees are the subject of Chapter 10. As mentioned
earlier, binary search trees are useful for storing data that needs to be stored orig‐
inally in sorted form.
• Chapter 11 covers graphs and graph algorithms. Graphs are used to represent data
such as the nodes of a computer network or the cities on a map.
• Chapter 12 moves from data structures to algorithms and discusses various algo‐
rithms for sorting data, including both simple sorting algorithms that are easy to
implement but are not efficient for large data sets, and more complex algorithms
that are appropriate for larger data sets.
• Chapter 13 also covers algorithms, this time searching algorithms such as sequential
search and binary search.
• The last chapter of the book, Chapter 14, discusses a couple more advanced algo‐
rithms for working with data—dynamic programming and greedy algorithms.
Preface | xi
www.it-ebooks.info
These algorithms are useful for solving hard problems where a more traditional
algorithm is either too slow or too hard to implement. We examine some classic
problems for both dynamic programming and greedy algorithms in the chapter.
xii | Preface
www.it-ebooks.info
Safari® Books Online
Safari Books Online is an on-demand digital library that
delivers expert content in both book and video form from
the world’s leading authors in technology and business.
Technology professionals, software developers, web designers, and business and crea‐
tive professionals use Safari Books Online as their primary resource for research, prob‐
lem solving, learning, and certification training.
Safari Books Online offers a range of product mixes and pricing programs for organi‐
zations, government agencies, and individuals. Subscribers have access to thousands of
books, training videos, and prepublication manuscripts in one fully searchable database
from publishers like O’Reilly Media, Prentice Hall Professional, Addison-Wesley Pro‐
fessional, Microsoft Press, Sams, Que, Peachpit Press, Focal Press, Cisco Press, John
Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe Press, FT
Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, Course Technol‐
ogy, and dozens more. For more information about Safari Books Online, please visit us
online.
How to Contact Us
Please address comments and questions concerning this book to the publisher:
We have a web page for this book, where we list errata, examples, and any additional
information. You can access this page at http://oreil.ly/data_structures_algorithms_JS.
To comment or ask technical questions about this book, send email to bookques
tions@oreilly.com.
For more information about our books, courses, conferences, and news, see our website
at http://www.oreilly.com.
Find us on Facebook: http://facebook.com/oreilly
Follow us on Twitter: http://twitter.com/oreillymedia
Watch us on YouTube: http://www.youtube.com/oreillymedia
Preface | xiii
www.it-ebooks.info
Acknowledgments
There are always lots of people to thank when you’ve finished writing a book. I’d like to
thank my acquisition editor, Simon St. Laurent, for believing in this book and getting
me started writing it. Meghan Blanchette worked hard to keep me on schedule, and if
I went off schedule, it definitely wasn’t her fault. Brian MacDonald worked extremely
hard to make this book as understandable as possible, and he helped make several parts
of the text much clearer than I had written them originally. I also want to thank my
technical reviewers for reading all the text as well as the code, and for pointing out places
where both my prose and my code needed to be clearer. My colleague and illustrator,
Cynthia Fehrenbach, did an outstanding job translating my chicken scratchings into
crisp, clear illustrations, and she deserves extra praise for her willingness to redraw
several illustrations at the very last minute. Finally, I’d like to thank all the people at
Mozilla for designing an excellent JavaScript engine and shell and writing some excellent
documentation for using both the language and the shell.
xiv | Preface
www.it-ebooks.info
CHAPTER 1
The JavaScript Programming Environment
and Model
This chapter describes the JavaScript programming environment and the programming
constructs we’ll use in this book to define the various data structures and algorithms
examined.
www.it-ebooks.info
js> for (var i = 1; i < 6; ++i) {
print(i);
}
1
2
3
4
5
js>
You can enter arithmetic expressions and the shell will immediately evaluate them. You
can write any legal JavaScript statement and the shell will immediately evaluate it as
well. The interactive shell is great for exploring JavaScript statements to discover how
they work. To leave the shell when you are finished, type the command quit().
The other way to use the shell is to have it interpret complete JavaScript programs. This
is how we will use the shell throughout the rest of the book.
To use the shell to intepret programs, you first have to create a file that contains a
JavaScript program. You can use any text editor, making sure you save the file as plain
text. The only requirement is that the file must have a .js extension. The shell has to see
this extension to know the file is a JavaScript program.
Once you have your file saved, you interpret it by typing the js command followed by
the full filename of your program. For example, if you saved the for loop code fragment
that’s shown earlier in a file named loop.js, you would enter the following:
c:\js>js loop.js
which would produce the following output:
1
2
3
4
5
After the program is executed, control is returned to the command prompt.
www.it-ebooks.info
Declaring and Intializing Variables
JavaScript variables are global by default and, strictly speaking, don’t have to be declared
before using. When a JavaScript variable is initialized without first being declared, it
becomes a global variable. In this book, however, we follow the convention used with
compiled languages such as C++ and Java by declaring all variables before their first
use. The added benefit to doing this is that declared variables are created as local vari‐
ables. We will talk more about variable scope later in this chapter.
To declare a variable in JavaScript, use the keyword var followed by a variable name,
and optionally, an assignment expression. Here are some examples:
var number;
var name;
var rate = 1.2;
var greeting = "Hello, world!";
var flag = false;
• + (addition)
• - (subtraction)
• * (multiplication)
• / (division)
• % (modulo)
JavaScript also has a math library you can use for advanced functions such as square
root, absolute value, and the trigonometric functions. The arithmetic operators follow
the standard order of operations, and parentheses can be used to modify that order.
Example 1-1 shows some examples of performing arithmetic in JavaScript, as well as
examples of using several of the mathematical functions.
Example 1-1. Arithmetic and math functions in JavaScript
var x = 3;
var y = 1.1;
print(x + y);
print(x * y);
print((x+y)*(x-y));
var z = 9;
print(Math.sqrt(z));
print(Math.abs(y/x));
www.it-ebooks.info
4.1
3.3000000000000003
7.789999999999999
3
0.3666666666666667
If you don’t want or need the precision shown above, you can format a number to a
fixed precision:
var x = 3;
var y = 1.1;
var z = x * y;
print(z.toFixed(2)); // displays 3.30
Decision Constructs
Decision constructs allow our programs to make decisions on what programming
statements to execute based on a Boolean expression. The two decision constructs we
use in this book are the if statement and the switch statement.
The if statement comes in three forms:
www.it-ebooks.info
else {
mid = (current+high) / 2;
}
The other decision structure we use in this book is the switch statement. This statement
provides a cleaner, more structured construction when you have several simple deci‐
sions to make. Example 1-5 demonstrates how the switch statement works.
www.it-ebooks.info
monthName = "July";
break;
case "8":
monthName = "August";
break;
case "9":
monthName = "September";
break;
case "10":
monthName = "October";
break;
case "11":
monthName = "November";
break;
case "12":
monthName = "December";
break;
default:
print("Bad input");
}
Is this the most efficient way to solve this problem? No, but it does a great job of dem‐
onstrating how the switch statement works.
One major difference between the JavaScript switch statement and switch statements
in other programming languages is that the expression that is being tested in the state‐
ment can be of any data type, as opposed to an integral data type, as required by languages
such as C++ and Java. In fact, you’ll notice in the previous example that we use the
month numbers as strings, rather than converting them to numbers, since we can com‐
pare strings using the switch statement in JavaScript.
Repetition Constructs
Many of the algorithms we study in this book are repetitive in nature. We use two
repetition constructs in this book—the while loop and the for loop.
When we want to execute a set of statements while a condition is true, we use a while
loop. Example 1-6 demonstrates how the while loop works.
www.it-ebooks.info
When we want to execute a set of statements a specified number of times, we use a for
loop. Example 1-7 uses a for loop to sum the integers 1 through 10.
for loops are also used frequently to access the elements of an array, as shown in
Example 1-8.
Functions
JavaScript provides the means to define both value-returning functions and functions
that don’t return values (sometimes called subprocedures or void functions).
Example 1-9 demonstrates how value-returning functions are defined and called in
JavaScript.
Example 1-9. A value-returning function
function factorial(number) {
var product = 1;
for (var i = number; i >= 1; --i) {
product *= i;
}
return product;
}
print(factorial(4)); // displays 24
print(factorial(5)); // displays 120
print(factorial(10)); // displays 3628800
Example 1-10 illustrates how to write a function that is used not for its return value, but
for the operations it performs.
www.it-ebooks.info
Example 1-10. A subprocedure or void function in JavaScript
function curve(arr, amount) {
for (var i = 0; i < arr.length; ++i) {
arr[i] += amount;
}
}
All function parameters in JavaScript are passed by value, and there are no reference
parameters. However, there are reference objects, such as arrays, which are passed to
functions by reference, as was demonstrated in Example 1-10.
Variable Scope
The scope of a variable refers to where in a program a variable’s value can be accessed.
The scope of a variable in JavaScript is defined as function scope. This means that a
variable’s value is visible within the function definition where the variable is declared
and defined and within any functions that are nested within that function.
When a variable is defined outside of a function, in the main program, the variable is
said to have global scope, which means its value can be accessed by any part of a program,
including functions. The following short program demonstrates how global scope
works:
function showScope() {
return scope;
}
The function showScope() can access the variable scope because scope is a global vari‐
able. Global variables can be declared at any place in a program, either before or after
function definitions.
Now watch what happens when we define a second scope variable within the show
Scope() function:
function showScope() {
var scope = "local";
return scope;
}
www.it-ebooks.info
The scope variable defined in the showScope() function has local scope, while the scope
variable defined in the main program is a global variable. Even though the two variables
have the same name, their scopes are different, and their values are different when
accessed within the area of the program where they are defined.
All of this behavior is normal and expected. However, it can all change if you leave off
the keyword var in the variable definitions. JavaScript allows you to define variables
without using the var keyword, but when you do, that variable automatically has global
scope, even if defined within a function.
Example 1-11 demonstrates the ramifications of leaving off the var keyword when
defining variables.
Example 1-11. The ramification of overusing global variables
function showScope() {
scope = "local";
return scope;
}
scope = "global";
print(scope); // displays "global"
print(showScope()); // displays "local"
print(scope); // displays "local"
In Example 1-11, because the scope variable inside the function is not declared with the
var keyword, when the string "local" is assigned to the variable, we are actually chang‐
ing the value of the scope variable in the main program. You should always begin every
definition of a variable with the var keyword to keep things like this from happening.
Earlier, we mentioned that JavaScript has function scope. This means that JavaScript
does not have block scope, unlike many other modern programming languages. With
block scope, you can declare a variable within a block of code and the variable is not
accessible outside of that block, as you typically see with a C++ or Java for loop:
for (int i = 1; i <=10; ++i) {
cout << "Hello, world!" << endl;
}
Even though JavaScript does not have block scope, we pretend like it does when we write
for loops in this book:
for (var i = 1; i <= 10; ++i ) {
print("Hello, world!");
}
We don’t want to be the cause of you picking up bad programming habits.
www.it-ebooks.info
Recursion
Function calls can be made recursively in JavaScript. The factorial() function defined
earlier can also be written recursively, like this:
function factorial(number) {
if (number == 1) {
return number;
}
else {
return number * factorial(number-1);
}
}
print(factorial(5));
When a function is called recursively, the results of the function’s computation are tem‐
porarily suspended while the recursion is in progress. To demonstrate how this works,
here is a diagram for the factorial() function when the argument passed to the func‐
tion is 5:
5 * factorial(4)
5 * 4 * factorial(3)
5 * 4 * 3 * factorial(2)
5 * 4 * 3 * 2 * factorial(1)
5 * 4 * 3 * 2 * 1
5 * 4 * 3 * 2
5 * 4 * 6
5 * 24
120
Several of the algorithms discussed in this book use recursion. For the most part, Java‐
Script is capable of handling fairly deep recursive calls (this is an example of a relatively
shallow recursive call); but in one or two situations, an algorithm requires a deeper
recursive call than JavaScript can handle and we instead pursue an iterative solution to
the algorithm. You should keep in mind that any function that uses recursion can be
rewritten in an iterative manner.
www.it-ebooks.info
function Checking(amount) {
this.balance = amount; // property
this.deposit = deposit; // function
this.withdraw = withdraw; // function
this.toString = toString; // function
}
The this keyword is used to tie each function and property to an object instance. Now
let’s look at the function definitions for the preceding declarations:
function deposit(amount) {
this.balance += amount;
}
function withdraw(amount) {
if (amount <= this.balance) {
this.balance -= amount;
}
if (amount > this.balance) {
print("Insufficient funds");
}
}
function toString() {
return "Balance: " + this.balance;
}
Again, we have to use the this keyword with the balance property in order for the
interpreter to know which object’s balance property we are referencing.
Example 1-12 provides the complete definition for the checking object along with a test
program.
function deposit(amount) {
this.balance += amount;
}
function withdraw(amount) {
if (amount <= this.balance) {
this.balance -= amount;
}
if (amount > this.balance) {
print("Insufficient funds");
}
www.it-ebooks.info
}
function toString() {
return "Balance: " + this.balance;
}
Summary
This chapter provided an overview of the way we use JavaScript throughout the rest of
the book. We try to follow a programming style that is common to many programmers
who are accustomed to using C-style languages such as C++ and Java. Of course, Java‐
Script has many conventions that do not follow the rules of those languages, and we
certainly point those out (such as the declaration and use of variables) and show you
the correct way to use the language. We also follow as many of the good JavaScript
programming practices outlined by authors such as John Resig, Douglas Crockford,
and others as we can. As responsible programmers, we need to keep in mind that it is
just as important that our programs be readable by humans as it is that they be correctly
executed by computers.
www.it-ebooks.info
CHAPTER 2
Arrays
The array is the most common data structure in computer programming. Every pro‐
gramming language includes some form of array. Because arrays are built-in, they are
usually very efficient and are considered good choices for many data storage purposes.
In this chapter we explore how arrays work in JavaScript and when to use them.
Using Arrays
Arrays in JavaScript are very flexible. There are several different ways to create arrays,
access array elements, and perform tasks such as searching and sorting the elements
stored in an array. JavaScript 1.5 also includes array functions that allow programmers
13
www.it-ebooks.info
to work with arrays using functional programming techniques. We demonstrate all of
these techniques in the following sections.
Creating Arrays
The simplest way to create an array is by declaring an array variable using the [] oper‐
ator:
var numbers = [];
When you create an array in this manner, you have an array with length of 0. You can
verify this by calling the built-in length property:
print(numbers.length); // displays 0
Another way to create an array is to declare an array variable with a set of elements
inside the [] operator:
var numbers = [1,2,3,4,5];
print(numbers.length); // displays 5
You can call the Array constructor with a set of elements as arguments to the constructor:
var numbers = new Array(1,2,3,4,5);
print(numbers.length); // displays 5
Finally, you can create an array by calling the Array constructor with a single argument
specifying the length of the array:
var numbers = new Array(10);
print(numbers.length); // displays 10
Unlike many other programming languages, but common for most scripting languages,
JavaScript array elements do not all have to be of the same type:
var objects = [1, "Joe", true, null];
We can verify that an object is an array by calling the Array.isArray() function, like
this:
var numbers = 3;
var arr = [7,4,1776];
print(Array.isArray(number)); // displays false
print(Array.isArray(arr)); // displays true
We’ve covered several techniques for creating arrays. As for which function is best, most
JavaScript experts recommend using the [] operator, saying it is more efficient than
14 | Chapter 2: Arrays
www.it-ebooks.info
calling the Array constructor (see JavaScript: The Definitive Guide [O’Reilly] and Java‐
Script: The Good Parts [O’Reilly]).
Array elements are also accessed using the [] operator. For example:
var numbers = [1,2,3,4,5];
var sum = numbers[0] + numbers[1] + numbers[2] + numbers[3] +
numbers[4];
print(sum); // displays 15
Of course, accessing all the elements of an array sequentially is much easier using a for
loop:
var numbers = [1,2,3,5,8,13,21];
var sum = 0;
for (var i = 0; i < numbers.length; ++i) {
sum += numbers[i];
}
print(sum); // displays 53
Notice that the for loop is controlled using the length property rather than an integer
literal. Because JavaScript arrays are objects, they can grow beyond the size specified
when they were created. By using the length property, which returns the number of
elements currently in the array, you can guarantee that your loop processes all array
elements.
Using Arrays | 15
www.it-ebooks.info
The output from this program is:
word 0: the
word 1: quick
word 2: brown
word 3: fox
word 4: jumped
word 5: over
word 6: the
word 7: lazy
word 8: dog
16 | Chapter 2: Arrays
www.it-ebooks.info
copy(nums, samenums);
nums[0] = 400;
print(samenums[0]); // displays 1
Another aggregate operation you can perform with arrays is displaying the contents of
an array using a function such as print(). For example:
var nums = [1,2,3,4,5];
print(nums);
will produce the following output:
1,2,3,4,5
This output may not be particularly useful, but you can use it to display the contents of
an array when all you need is a simple list.
Accessor Functions
JavaScript provides a set of functions you can use to access the elements of an array.
These functions, called accessor functions, return some representation of the target array
as their return values.
If you run this program and enter Cynthia, the program will output:
Found Cynthia at position 1
Accessor Functions | 17
www.it-ebooks.info
If you have multiple occurrences of the same data in an array, the indexOf() function
will always return the position of the first occurrence. A similar function, lastIndex
Of(), will return the position of the last occurrence of the argument in the array, or -1
if the argument isn’t found. Here is an example:
var names = ["David", "Mike", "Cynthia", "Raymond", "Clayton", "Mike",
"Jennifer"];
var name = "Mike";
var firstPos = names.indexOf(name);
print("First found " + name + " at position " + firstPos);
var lastPos = names.lastIndexOf(name);
print("Last found " + name + " at position " + lastPos);
The output from this program is:
First found Mike at position 1
Last found Mike at position 5
When you call the print() function with an array name, it automatically calls the
toString() function for that array:
print(names); // David,Cynthia,Raymond,Clayton,Mike,Jennifer
18 | Chapter 2: Arrays
www.it-ebooks.info
itDiv = dmp.concat(cisDept);
print(itDiv);
The program outputs:
Mike,Clayton,Terrill,Danny,Jennifer,Raymond,Cynthia,Bryan
Raymond,Cynthia,Bryan,Mike,Clayton,Terrill,Danny,Jennifer
The first output line shows the data from the cis array first, and the second output line
shows the data from the dmp array first.
The splice() function creates a new array from the contents of an existing array. The
arguments to the function are the starting position for taking the splice and the number
of elements to take from the existing array. Here is how the method works:
var itDiv = ["Mike","Clayton","Terrill","Raymond","Cynthia","Danny","Jennifer"];
var dmpDept = itDiv.splice(3,3);
var cisDept = itDiv;
print(dmpDept); // Raymond,Cynthia,Danny
print(cisDept); // Mike,Clayton,Terrill,Jennifer
There are other uses for splice() as well, such as modifying an array by adding
and/or removing elements. See the Mozilla Developer Network website for more in‐
formation.
Mutator Functions
JavaScript has a set of mutator functions that allow you to modify the contents of an
array without referencing the individual elements. These functions often make hard
techniques easy, as you’ll see below.
Using push() is more intuitive than using the length property to extend an array:
var nums = [1,2,3,4,5];
print(nums); // 1,2,3,4,5
nums[nums.length] = 6;
print(nums); // 1,2,3,4,5,6
Adding data to the beginning of an array is much harder than adding data to the end
of an array. To do so without the benefit of a mutator function, each existing element
Mutator Functions | 19
www.it-ebooks.info
Another Random Document on
Scribd Without Any Related Topics
– De nem tehette azt; mert amint a kunyhóajtóból előlép, a kunyhó
tetején ácsingózó ordas egyszerre le fog rá ugrani s hátulról rántja
le.
Guthay Lőrincz karra vetett puskával nézte ezt az ádáz
küzdelmet.
Bizony ordália ez! Istenitélet. Ime előjöttek azok a vadak, a kik
Eliézer megcsúfolóit összetépték; a sors azok által tesz igazságot. Itt
most össze fogják tépni, széthurczolni azt a halálos ellenséget, a
kinek kiengesztelhetetlen haragja, akinek gonosz luxuriese az ő
életét követelte áldozatul. A saját életét veszti el.
Neki nem kell egyebet tenni, mint nézni. Elnézni a halálos tusáját,
kétségbeesését annak a másiknak.
De hát el fogja-e ezt viselni az ő lelke?
A kétségbeesésnek e paroxismusában elordítá magát Kadarkuthy:
«ember! segíts!»
A borzasztó, emberéhez nem hasonlitó üvöltést viszhangozá a
mogyoróliget fala.
Arra két lövés dördült el, pillanatnyi közökben.
Az egyik lövésre a gunyhó tetején leskelődő farkas bukfenczezett
le Kadarkuthy lába elé, a másikra a havat szóró ordas vágta magát
hanyatt, négy lábával kalimpázva. Guthay Lőrincz «holó–holó–holó!»
kiáltozással rohant elő a bükkfa mellől szuronyos fegyverével, mire
az ugrásra készülő ordas egyszerre felriadt, oldalt szökött, s aztán
odarohanva a bezuzott orru párjához, annak megkapta a fülét, s ugy
vonszolta el magával a fülénél fogva: lompos farkával ütögetve hátul
gyorsabb szaladásra. Eltüntek a bozótban.
– Nem törött el a puskaagy? – Ez volt az első szava Guthay
Lőrincznek Kadarkuthy Viktorhoz.
A kérdezett szótlanúl mutatta a fegyverét: ép volt.
– Akkor hát újra megtölthetjük a puskáinkat s kezdhetjük a
párbajt.
Kadarkuthy erre a szóra eldobta a puskát a kezéből.
– Jaj, ne beszélj róla, – rebegé fogvaczogva. – Hiszen úgy
reszketek. A hideg ráz. Fogd meg a kezemet.
Odanyújtá a kezét Guthay Lőrincznek. Olyan hideg volt az, mint
egy halottnak a keze.
– Csinálj tüzet inkább.
A lévita erre odament a lesgunyhóhoz, fölnyitotta annak az
ajtaját. A puskavesszővel kellett benyúlni az ajtó likán s úgy emelni
föl a reteszt. Odabenn aztán volt tűzszerszám. A gunyhó közelében
volt fölmáglyázva a targaly, azt csak meg kellett gyújtani az égő
csóvával: a tűz vigan ropogva égett.
Kadarkuthy Viktor térdre ereszkedett a tűz mellé, s kezeit
összetette a mellén: fázott, reszketett. Szemei merően bámultak a
lobogó tűzbe; még most is a pokoli rémképeket látta maga előtt.
Ajkai valamit motyogtak csendesen: «van Isten! van Isten!»
Azután odainté Lőrinczet.
– Ülj mellém. Ölelj meg. Úgy reszketek. Nincsen egy csöpp
szivem sem. Megették a farkasok! Ne hagyj nekik széttépni!
Guthay Lőrincz odaült a térdeplő férfi mellé s átölelte annak a
vállát.
– Ne félj! Elvertük a czudár bestiákat. Ott hevernek a havon.
Kettőt te öltél meg, kettőt én.
Erre a szóra elkezdett Kadarkuthynak az arcza nyavalyatörős
vigyorgásra torzulni.
– Azokban laktak az ördögök, – suttogá. – A mi lelkünket
megszálló ördögök. Most megszabadultunk tőlük. Úgy-e nem fogunk
egymásra haragudni többé soha?
Guthay Lőrincz mély megilletődést érzett. Valami nagy változást
vett észre Kadarkuthyn, mely külső jelben tanusítá a nagy lelki
fordulatot; de nem szólt neki felőle.
Kadarkuthy odahúzta magához Guthay fejét, hogy a fülébe
súghassa:
– Én teneked a lelkemmel tartozom. Te a lelkemet adtad vissza.
Eddig nem volt.
A lévita vette észre, hogy vadásztársa félrebeszél.
Hirtelen fölvett egy marék havat s azzal erősen bedörzsölte
annak az arczát, orrát, füleit. Ettől magához tért.
– Köszönöm, pajtás! – szólt aztán régi szokott hangján. – Nagyon
elcsigázott ez a hajczihő. Most már eszemen vagyok. Nem fogok
bolondokat beszélni. Te kiegyenlítetted a tartozásodat ellenemben;
de én még nem, a mivel neked tartozom. Eredj haza a feleségedhez,
s mondd el neki, hogy az ő férjét nem üldözi senki a világon többé.
Te visszatérhetsz az emberi társaságba. Asszonyoddal
megesküdhetel igaz hit szerint, hogy viselje a te nevedet. Szülőid
meghaltak. Az öreg Malárdyból alázatos ember lett. Fia elvette a te
szülőid fogadott leányát. A két család közti átok megszünt. A
feleséged szép vagyont örökölt; Durday őrnagy ráhagyta egész
birtokát, ha tíz év alatt elő fog kerülni. Ellenkező esetben a városi
kórház alapítványáúl fog az szolgálni. Ezentúl gond nélkül élhettek
szülővárosodban; te a tudományoknak élhetsz, tisztességes állást
szerezhetsz; egy makula nem lesz a neveden. Én úgy elhagyom ezt
az országot, hogy soha vissza nem térek többet. Én megbocsátottam
neked s másnak nincs megbocsátani valója.
Guthay Lőrincz megszorítá Kadarkuthy Viktor feléje nyujtott
kezét; most már forró volt az.
– A bocsánatot köszönöm, ezt örömmel fogadom. De azon túl
semmit. Én a feleségemnek el nem mondhatom ennek a mostani
órának a történetét; mert azzal egész életére szerencsétlenné
tenném. Ő pedig most boldog, meg van elégedve. S az ő boldogsága
az én sorsom is. A birtokra, a mit neki hagyományoztak, a város
gyámoltalan lázárainak szüksége van, nekünk nincs. A mi kenyerünk
hiveink szivében van s az jó termő föld. A fiamat arra fogom nevelni,
hogy esze és szorgalma után megéljen. A pénz elgurúl, a földbirtok
elszalad a kényeztetett úrfiak kezéből és lába alól; hanem a szegény
ember fiának a munkakedve dominium és capitalis, a mi nem vész el
soha. Mi itt maradunk a barátfalvi völgyben. Külömbség csak az lesz
ránk nézve, hogy most már ki is járhatunk belőle.
– Így is jó, – mondá Kadarkuthy fölállva a tűz mellől. – Most hát
töltsük meg újra a fegyvereinket s aztán te majd vezess el a
kocsiutig, a melyen Szent Péterre eljutok, a hol egy emberem vár
reám, a kivel tudatnom kell, hogy élek.
– Hanem előbb ezeket az elejtett farkasokat czipeljük be a
lesgunyhóba, mert ez most rám nézve egy capitalis, a mivel ki lesz
elégítve az orgonácskám ára.
– Félsz, hogy ellopja valaki őket?
– Nem valaki, de valami. A farkasok visszajönnek s a megölt
pajtásaikat fölfalják.
– Ah! A kannibálok? A saját testvéreiket.
– Te soha sem láttál farkast?
– Soha! Hiszen Párisból jövök, s ott «louve»-nak a fortificatio
nimfáit hívják.
– Akkor elég jól viselted magadat a farkasok első rendez-vous-
jában.
Azzal aztán segített Kadarkuthy Guthaynak a vadászzsákmányt a
lesgunyhóba behordani. Majd holnap eljönnek a munkások a
bundáikért.
– De biz ezt a kis ártatlan malaczot sem hagyom itt prédára, –
mondá a lévita s odament a hangafa bokorhoz. A kis malacznak már
volt annyi esze, hogy a nagy farkasvonítás közben meg ne
nyikkanjon, hanem elbújjon a páfrán közé. – Majd mikor a falú
végéhez érünk, kieresztem a zsákból; hazatalál ez magától.
Azután sáscsutakból fáklyákat készítettek a vadászok, s azokat
meggyújtva, hatoltak ki a veszedelmes völgyből, föl a vízválasztóig.
A szekérútnál, a keresztfa előtt, megölelték egymást, úgy váltak el.
Hermina soha sem tudta meg, hogy mi történt ezen a
réméjszakán, a farkasok völgyében.
MI VOLT AZ A NAGY VÁLTOZÁS?
Á
egész Magyarország. Áldása az áldatlan földnek! Ez az a fa, a mely
minden mostoha talajban meghonosúl, olyanokban, a mikben már a
vad cziher sem marad meg, s aztán tavaszszal elárasztja tündér
illatával az egész vidéket s gazdagítja édes mézzel a méhköpüket.
Ezzel az akáczfa-maggal Guthay Lőrincz visszavivta a hivei
számára a záporásta szántóföldek területét, hogy ismét boldog
szántóvetők lehettek, örülhettek a kalászérésnek és aratásnak.
S vannak emberek, a kiknek ez is öröm.
UJABB ELBESZÉLÉSEK.
NAZLI-HÁNEM.
(Elbeszélés.)
Hárman ültek együtt a hosszú terített asztalnak a végén az
«Angol királynő» vendégfogadó földszinti étkezőszobáinak
egyikében, ott, a hol a képviselőház elnöke szokta tartani a
képviselői lakomát.
Az asztalon tizenkét tányér volt, megfelelő étkező szerekkel,
poharakkal, nyomtatott fogásrenddel és vékony pohárkákba dugott
thearozsákkal. Az asztalkendők dinnye alakú gerezdekbe hajlítva a
tányérokon.
Tizenkét teríték az asztalon és csak hárman ülnek az asztal
végén? Ennek a magyarázata az, hogy már elmúlt két óra, a mi
rendes viszonyaink szerint túlhaladott álláspontja az ebédkezdés
idejének. Még várnak valakit, vagy valakiket, de addig is
«domitorium»-nak hozzálátnak a jó szerémi szilvapálinkához, a mit
miskolczi gyürkés czipóval nyomtatnak le. Ez csak sarkantyút ád az
étvágynak.
A ki az asztalfön ül, az egy előkelő fővárosi ügyvéd; a feje
egészen kopasz, alig billeng fülei mögött egy-egy kondor bibolácska,
a minek az a szokása, hogy soha sem őszül meg, makacsul
megmarad gesztenyeszinűnek, a mi némi ellenmondást képez a
felkunkorított bajuszszal, mely koromszínű. Ez szabad: a bajuszt
koromszinűre festeni. Szakáll, haj, szemöldök mind követheti a maga
változatosság iránti szabad akaratát; de a bajusz a miénk, annak mi
parancsolunk. Különben a szakáll sem a maga ura, annak is van
törvénye, a borotva: az learattatik. Az arcz piros és sima. Látszik,
hogy jól van táplálva. Csak a szemek árulják el az előhaladott kort. A
szemhéjak duzzadtak, s a látószereknek két szemüvegre van
szükségük, az egyik az orrcsiptető, mely az olvasáshoz szükséges, a
másik a fülbekapaszkodó pápaszem, melylyel távolba lehet látni;
szobában azt a homlokra feltolva viselik.
A matrózhurokra kötött fehér nyakravalóba egyszerű
gyémántgombos melltű van nyársalva; a mellény sárga pikét,
oldalzsebéből lecsüggő nehéz aranylánczczal, melynek végét kárniól
pecsétnyomó, ezüst Szent György-tallér korallkéz, arany plajbásztok,
aczél szivarvégcsikkentő és kisded aneroid húzzák lefelé. A hátra
nyesett szárnyú dohányzó kabát oldalzsebéből sárgavörös keztyű
újjai kandikálnak elő.
Ez a házigazda, a ki a kupiczákba töltöget.
A másik kettő a meghivott vendég.
A jobbkéz felől ültetett vendég alacsony, köpczös termetű férfi,
szürke, kurta zekében, melynek a gallérja hiúzprém. A zeke
ezüstgombos és zsinórra jár: de most ki van gombolva, mert ebéd
előtt ez így tanácsos; az előre domborodó testrész ezt megkívánja,
melyet nem egész akkurátusan fedez a kalotaszegi varrottas mellény,
úgy hogy az alatt a következő csattos szíj lyukait meg lehet
számlálni. (Majd később szaporodni fognak.) Természetesen zsinóros
magyar nadrágot s gombfejü sarkantyús csizmát visel. Inggallérja és
ingeleje koczkás rózsaszínű vászon, virágos himzésekkel. Arcza,
homloka széles, naptól égett kordovánszínű, a mitől erősen elüt a
gunár ősz haj gubanczos volta, s a sárgára őszült szakáll, meg a
fakóvá pipázott bajusz. Az arcz kifejezése mérgesen jókedvű.
A második vendég, a ki balfelől ül, háttal van felénk fordulva; de
az elejéből sem ismerjük meg jobban, mert iparkodik az arczát
mindig lefelé hajtani, mintha keresne a földön valamit; homlokát a
tenyerébe támasztja, s a száját csak akkor nyítja föl, a mikor a
kupiczát kihörpinti. Arczvonásai kemények, bőrré váltak, rajta a
szőrféle, úgynevezett koldússzakáll, rövid borostásra nyirva; ilyen a
haja is, rövid, sűrű, elől homlokig, hátúl nyakig benőve. Fekete
selyem nyakkendője az ádámcsutkáig föltekerve; viseléstől fényes
fekete kabátja végig begombolva.
– Ugyan szép volt tőletek, hogy eljöttetek a meghivásomra, fiúk!
(fiúk!) szólt a házi gazda, összekoczintva kupiczáját a két szál
vendégével.
– Hát hogyne jöttünk volna? monda a zöldszakállú. A kiben egy
csepp magyar vér buzog, csak feljön a millennáris kiállításra; ámbár
az ilyen gazdaféle embernek, mint magam, ilyenkor van a
legsürgősebb dolga odahaza. Most gépelik a repczét. No, de otthon
van a fiam, utána lát a dolognak, nem kell miatta aggódnom.
– A fiadból is mezei gazdát csináltál? Nagyon helyes.
– Höher Péter! A fiam diplomás ember.
– Miféle diplomája van?
– Hát gépész diplomája. Gépésznek taníttattam ki. Igy aztán
rábizhatom az egész gazdaságot.
Erre aztán a koldús-szakállú is megszólalt.
– Hát bizony engem is a fiam segített ki, hogy erre a szent napra
feljöhessek Bergengócziából a szép fővárosba.
– A fiad is néptanító?
– Egygyel feljebb. Az már lelkész. Káplán a legjobb dotáczióval
biró helységében a Bakonynak. Nagyon szeretik a hivek. Ha az öreg
testál, pedig közel van már hozzá, megmarasztják papnak. Most
távollétemben ő szolgál helyettem. A scytháknak ugyan most már
vakácziójuk van; de a hivek megkivánják a mindennapi beéneklést.
– No, csakhogy eljöttetek, szólt két kezét egyszerre nyújtva a
vendégeinek az ügyvéd.