Learning Javascript Data Structures and Algorithms
Learning Javascript Data Structures and Algorithms
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
www.packtpub.com
http://loiane.com
https://www.facebook.c
om/loianegroner @loiane https://github.com/loia
ne
@tessaract
http://tessaract.info
www.PacktPub.com
customercare@packtpub.com
www.PacktPub.com
https://www2.packtpub.com/books/subscription/packtlib
2
Chapter 1
Chapter 2
Chapter 3
Chapter 4
Chapter 5
Chapter 6
Chapter 7
Chapter 8
Chapter 9
Chapter 10
Chapter 11
Chapter 12
https://www.google.com/chrome/browser/
https://www.mozilla.org/en-US/firefox/new/
https://www.apachefriends.org
http://nodejs.org/
http-server
isEmpty
function Stack() {
//properties and methods go here
}
class Stack {
push(element){
this.items.push(element);
}
//other methods
}
feedback@packtpub.com
www.packtpub.com/authors
http://www.
packtpub.com http://www.packtpu
b.com/support
https://github.com/loiane/
javascript-datastructures-algorithms
https://github.com/PacktPublishing/
https://www.packtpub.com/sites/default/files/
downloads/LearningJavaScriptDataStructuresandAlgorithmsSecondEdition_Co
lorImages.pdf
http://www.packtpub.com/submit-errata
https://www.packtpub.com/books/con
tent/support
copyright@packtpub.com
questions@packtpub.com
https://github.com
http://goo.gl/ZFx6m
g
https://www.npmjs.org/
https://getfire
bug.com/
https://www.apachefriends.org
htdocs
htdocs
http://nodejs.org/
http-server
http-server
http-server
https://github.com/loiane/javascript-data
structures-algorithms
https://github.com/Pack
tPublishing/
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<script>
alert('Hello, World!');
</script>
</body>
</html>
script
script
01-
HelloWorld.js
alert('Hello, World!');
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<script src="01-HelloWorld.js">
</script>
</body>
</html>
include
head
body
int num = 1; var
{1}
var
{2}
{3}
{4} {5}
{6} null {7}
null undefined
console.log
console.log
console.log("num: "+ num) console.log("num: ", num)
function myFunction(){
var myVariable = 'local';
return myVariable;
}
function myOtherFunction(){
myOtherVariable = 'local';
return myOtherVariable;
}
console.log(myVariable); //{1}
console.log(myFunction()); //{2}
console.log(myOtherVariable); //{3}
console.log(myOtherFunction()); //{4}
console.log(myOtherVariable); //{5}
num += 1; // {2}
num -= 2;
num *= 3;
num /= 2;
num %= 3;
{1}
+
-
*
/
%
++
--
{2}
=
+=
-=
*=
/=
%=
{3}
==
===
!=
>
>=
<
<=
{4}
&&
||
!
&
|
~
^
<<
>>
typeof
delete
true false
false
false
true false
false +0 -0 NaN true
false
true
true
function testTruthy(val){
return val console.log('truthy') : console.log('falsy');
}
testTruthy(true); //true
testTruthy(false); //false
testTruthy(new Boolean(false)); //true (object is always true)
testTruthy(''); //false
testTruthy('Packt'); //true
testTruthy(new String('')); //true (object is always true)
testTruthy(1); //true
testTruthy(-1); //true
testTruthy(NaN); //false
testTruthy(new Number(NaN)); //true (object is always true)
true
true
x == toNumber(y)
toNumber(x) == y
toNumber(x) == y
x == toNumber(y)
x == toPrimitive(y)
toPrimitive(x) == y
equals
toNumber toPrimitive
toNumber
NaN
+0
true 1 false +0
NaN
toNumber(toPrimitive(value))
toPrimitive
valueOf
toString
true
console.log('packt' == true);
false
toNumber packt == 1
toNumber
NaN NaN == 1
console.log('packt' == false);
false
toNumber packt == 0
toNumber
NaN NaN == 0
===
NaN true
true
true false true
true
if...else
if...else
if true
var num = 1;
if (num === 1) {
console.log("num is equal to 1");
}
if...else
true false else
var num = 0;
if (num === 1) {
console.log("num is equal to 1");
} else {
console.log("num is not equal to 1, the value of num is " + num);
}
if...else
if...else
if...else
var month = 5;
if (month === 1) {
console.log("January");
} else if (month === 2){
console.log("February");
} else if (month === 3){
console.log("March");
} else {
console.log("Month is not January, February or March");
}
switch
switch
var month = 5;
switch(month) {
case 1:
console.log("January");
break;
case 2:
console.log("February");
break;
case 3:
console.log("March");
break;
default:
console.log("Month is not January, February or March");
}
for
for
for
for i
i 10 i
while
while
i i
i
var i = 0;
while(i<10)
{
console.log(i);
i++;
}
do...while while
while
do...while
do...while
var i = 0;
do {
console.log(i);
i++;
} while (i<10)
return
function sayHello() {
console.log('Hello!');
}
sayHello();
function output(text) {
console.log(text);
}
output('Hello!');
obj = {
name: {
first: 'Gandalf',
last: 'the Grey'
},
address: 'Middle Earth'
};
Stack Set LinkedList
Dictionary Tree Graph
Book.prototype.printTitle = function(){
console.log(this.title);
};
book.printTitle();
https://develop
er.chrome.com/devtools/docs/javascript-debugging
http://www.aptana.com/
http://www.jetbrains.com/webstorm/
http://www.sublimetext.com/
https
://atom.io/
http://kangax.github.io/compat-table/es6/
http://kangax.github.io/compat-table/es7/
chrome://flags
https://babeljs.io
https://babeljs.io/docs/setup/
https://babeljs.io/repl/
let const
=>
var framework = 'Angular';
var framework = 'React';
console.log(framework);
React
let var
var let
{2}
{1} let
https://goo.gl/he0udZ
let
https://goo.gl/NbsVvg
function starWarsFan(){
let movie = 'Star Wars'; //{2}
return movie;
}
function marvelFan(){
movie = 'The Avengers'; //{3}
return movie;
}
function blizzardFan(){
let isFan = true;
let phrase = 'Warcraft'; //{4}
console.log('Before if: ' + phrase);
if (isFan){
let phrase = 'initial text'; //{5}
phrase = 'For the Horde!'; //{6}
console.log('Inside if: ' + phrase);
}
phrase = 'For the Alliance!'; //{7}
console.log('After if: ' + phrase);
}
console.log(movie); //{8}
console.log(starWarsFan()); //{9}
console.log(marvelFan()); //{10}
console.log(movie); //{11}
blizzardFan(); //{12}
{9} starWarsFan
movie {2}
Star Wars {2}
{10} marvelFan
movie {3}
{1}
The Avengers {10} {11}
blizzardFan {12}
phrase {4}
{5} phrase
if
{6} phrase if
{5}
{7} phrase
if {4}
const let
const
const PI = 3.141593;
PI = 3.0; //throws error
console.log(PI);
PI var PI let PI
PI
https://goo.gl/4xuWrC
var book = {
name: 'Learning JavaScript DataStructures and Algorithms'
};
console.log
`
${}
book.name
\n
and
this is a new line
https://goo.gl/PTqnwO
{1}
=>
return
https://goo.gl/CigniJ
function sum (x = 1, y = 2, z = 3) {
return x + y + z
};
console.log(sum(4,2)); //outputs 9
z 4 + 2 + 3 ==
9
https://goo.gl/2MiJ59
apply()
...
x y z
...
arguments
https://goo.gl/8equk
5 https://goo.gl/L
aJZqU
var [x, y] = ['a', 'b'];
var x = 'a';
var y = 'b';
var temp = x;
x = y;
y = temp;
var x = 'a';
var y = 'b';
var obj2 = { x: x, y: y };
console.log(obj2); // { x: "a", y: "b" }
var hello = {
name : 'abcdef',
printHello(){
console.log('Hello');
}
}
console.log(hello.printHello());
var hello = {
name: 'abcdef',
printHello: function printHello() {
console.log('Hello');
}
};
https://goo.gl/VsLecp
https://goo.gl/EyFAII
https://goo.gl/DKU2PN
Book
https://goo.gl/UhK1n4
extends {1}
constructor
super {2}
https://goo.gl/hgQvo9
get set
class Person {
constructor (name) {
this._name = name; //{1}
}
get name() { //{2}
return this._name;
}
set name(value) { //{3}
this._name = value;
}
}
{1}
get set
{4} {5}
_name
https://goo.gl/SMRYsv
http://www.ecma-international.org/ecma-26
2/6.0/
Array.prototype.includes
Object.values Object.entries
Math.pow(2, 3) 2 ** 3 **
Array.prototype.includes
Chapter 2
https://tc39.github.io/ecma2
62/
https://github.com/loiane/javascript-datastructures-algo
rithms
averageTemp
new {1}
new
{2}
{3}
new
[]
length
7
daysOfWeek
{1}
{2} {3}
{4}
{6}
{5}
console.log {5}
{6} console.log(fibonacci)
console.log
20
numbers[numbers.length] = 10;
push
push
numbers.push(11);
numbers.push(12, 13);
numbers
+ 1
-1
for (var i=numbers.length; i>=0; i--){
numbers[i] = numbers[i-1];
}
numbers[0] = -1;
array unshift
numbers.unshift(-2);
numbers.unshift(-4, -3);
unshift -2 -3 -4
numbers
pop
numbers.pop();
push pop stack
i+1
numbers.length -1
shift
numbers.shift();
splice
numbers.splice(5,3);
delete
remove
numbers[0]
undefined numbers[0] =
undefined splice pop
shift
splice
numbers.splice(5,0,2,3,4);
numbers.splice(5,3,2,3,4);
function printMatrix(myMatrix) {
for (var i=0; i<myMatrix.length; i++){
for (var j=0; j<myMatrix[i].length; j++){
console.log(myMatrix[i][j]);
}
}
}
for
i j
averageTemp
printMatrix(averageTemp);
i j z
for
concat
every
false
filter true
forEach
join
indexOf
lastIndexOf
map
reverse
slice
some
true
sort
toString
valueOf toString
concat
var zero = 0;
var positiveNumbers = [1,2,3];
var negativeNumbers = [-3,-2,-1];
var numbers = negativeNumbers.concat(zero, positiveNumbers);
zero negativeNumbers
positiveNumbers numbers
for
true
false
every every
false
numbers.every(isEven);
numbers
isEven false
some every
some true
numbers.some(isEven);
numbers
false
true
forEach
for
numbers.forEach(function(x){
console.log((x % 2 == 0));
});
map
filter
true
evenNumbers [2,
4, 6, 8, 10, 12, 14]
reduce reduce
previousValue currentValue index array
reduce
Array map
reduce map
reduce
Chapter 1
@@iterator
copyWithin
entries @@iterator
includes true false
find
findIndex
fill
from
keys @@iterator
of
values @@iterator
for..of
forEach
numbers.forEach(function (x) {
console.log(x % 2 == 0);
});
numbers.forEach(x => {
console.log((x % 2 == 0));
});
for forEach
for..of
for..of
https://goo.gl/qHYAN1
Array @@iterator
Symbol.iterator
next
iterator.next()
iterator.next() undefined
numbers.value()
https://goo.gl/L81UQW
entries
entries @@iterator
number key
value
keys @@iterator
numbers keys
aKeys.next() undefined value done true
done false
values @@iterator
https://goo.gl/eojEGk
Array.from
https://goo.gl/n4rOY4
Array.of
Array.from(numbers4)
spread Chapter 1
... numbers4
https://goo.gl/FoJYNf
fill
numbersCopy.fill(0);
numbersCopy [0,0,0,0,0,0]
numbersCopy.fill(2, 1);
2
1 [0,2,2,2,2,2]
numbersCopy.fill(1, 3, 5);
1 3 5
[0,2,2,1,1,2]
fill
6 1 [1,1,1,1,1,1]
https://goo.gl/sqiHSK
copyWithin
45 6
[4,5,6,4,5,6]
copyArray.copyWithin(0, 3);
4 5
[1,4,5,4,5,6]
https://goo.gl/hZhBE1
numbers
reverse
numbers.reverse();
numbers.sort();
numbers.sort(function(a,b){
return a-b;
});
b a a
b
a b sort
function compare(a, b) {
if (a < b) {
return -1;
}
if (a > b) {
return 1;
}
// a must be equal to b
return 0;
}
numbers.sort(compare);
sort Array
compareFunction
compareFunction
var friends = [
{name: 'John', age: 30},
{name: 'Ana', age: 20},
{name: 'Chris', age: 25}
];
console.log(friends.sort(comparePerson));
ana John
http://www.asciitab
le.com/
compareFunction
["Ana", "ana", "John", "john"]
names.sort(function(a, b){
if (a.toLowerCase() < b.toLowerCase()){
return -1
}
if (a.toLowerCase() > b.toLowerCase()){
return 1
}
return 0;
});
localeCompare
["Maeve", "Maève"]
indexOf
lastIndexOf
numbers
console.log(numbers.indexOf(10));
console.log(numbers.indexOf(100));
9 -1
numbers.push(10);
console.log(numbers.lastIndexOf(10));
console.log(numbers.lastIndexOf(100));
10 15
-1
100
undefined
https://goo.gl/2vAaCh
console.log(numbers.includes(15));
console.log(numbers.includes(20));
false 4
5
https://goo.gl/tTY9bc
toString join
toString
console.log(numbers.toString());
- join
http://www.w3school
s.com/js/js_arrays.asp
http://www
.w3schools.com/js/js_array_methods.asp
https://developer.mozilla.org/en-US/docs/Web/Jav
aScript/Reference/Global_Objects/Array http://goo.gl/vu1d
iT
http://underscorejs.org/
http://lodash.com/
TypeArray
let myArray = new TypedArray(length) TypedArray
TypedArray
Int8Array
Uint8Array
Uint8ClampedArray
Int16Array
Uint16Array
Int32Array
Uint32Array
Float32Array
Float64Array
let length = 5;
let int16 = new Int16Array(length);
Array
function Stack() {
//properties and methods go here
}
push(element(s))
pop()
peek()
isEmpty()
clear()
size()
length
push
push
this.push = function(element){
items.push(element);
};
push
array
pop
pop
array pop
this.pop = function(){
return items.pop();
};
push pop
Stack
helper
peek
this.peek = function(){
return items[items.length-1];
};
length - 1
length - 1
isEmpty true
false
this.isEmpty = function(){
return items.length == 0;
};
isEmpty
length array length
Stack size length
length
this.size = function(){
return items.length;
};
clear clear
this.clear = function(){
items = [];
};
pop
Stack
helper print
this.print = function(){
console.log(items.toString());
};
Stack
Stack
true,
peek 8
11 size 3
5 8 11 isEmpty
false
push
pop
pop
pop 5 8
pop
Stack
items
private Stack
items
Stack
Stack
class Stack {
push(element){
this.items.push(element);
}
//other methods
}
Stack Stack
constructor
{1} this.nameofVariable
items public
private
Stack
Symbol
items Stack
class Stack {
constructor () {
}
//Stack methods
}
Object.getOwnPropertySymbols
Symbols
Stack
_items
stack[objectSymbols[0]] _items
WeakMap Chapter 7
WeakMap
Stack WeakMap
class Stack {
constructor () {
}
push(element){
let s = items.get(this); //{3}
s.push(element);
}
pop(){
let s = items.get(this);
let r = s.pop();
return r;
}
//other methods
}
{1}, WeakMap
{2} items
Stack WeakMap
{3}, items
WeakMap {2}
items Stack
items Stack
Stack closure
WeakMap
Stack Stack
{5}
http://www.w3scho
ols.com/js/js_function_closures.asp
Stack items
Stack
function Stack() {
let items = [];
//other methods
}
WeakMap
Stack
function divideBy2(decNumber){
return binaryString;
}
{1}
{2} {3}
{4}
Math.floor
{5}
function baseConverter(decNumber, base){
while (!remStack.isEmpty()){
baseString += digits[remStack.pop()]; //{7}
}
return baseString;
}
{6} {7}
push pop
function Queue() {
//properties and methods go here
}
Stack
Queue Stack
enqueue(element(s))
dequeue()
front()
peek Stack
isEmpty() true
false
size()
length
enqueue
this.enqueue = function(element){
items.push(element);
};
push
array Chapter 2 Chapter
3
dequeue
shift
array Chapter 2
shift
this.dequeue = function(){
return items.shift();
};
enqueue dequeue
Queue
helper
front
this.front = function(){
return items[0];
};
isEmpty true
false Stack
this.isEmpty = function(){
return items.length == 0;
};
isEmpty
length array
Queue size Stack
this.size = function(){
return items.length;
};
Queue Stack
print
this.print = function(){
console.log(items.toString());
};
Queue Stack
dequeue front
Queue
true
enqueue
dequeue dequeue
dequeue
Camila
Chapter 3 Queue
WeakMap items
closure Queue
class Queue2 {
constructor () {
items.set(this, []);
}
enqueue(element) {
let q = items.get(this);
q.push(element);
}
dequeue() {
let q = items.get(this);
let r = q.shift();
return r;
}
//other methods
}
return Queue2;
})();
Queue
dequeue
function PriorityQueue() {
let items = [];
function QueueElement (element, priority){ // {1}
this.element = element;
this.priority = priority;
}
this.print = function(){
for (let i=0; i<items.length; i++){
console.log(`${items[i].element} -
${items[i].priority}`);
}
};
//other methods - same as default Queue implementation
}
Queue PriorityQueue
{1} PriorityQueue
{2}
splice
array Chapter 2
{3}
{4}
{5}
PriorityQueue
John 2
Jack 1 Jack
John Camila
1 Camila Jack Jack
Camila John
function hotPotato (nameList, num){
Queue
{1}
{2}
{3}
{4}
{5}
hotPotato
https://goo.gl/ayF840
queue
enqueue dequeue
Chapter 2
LinkedList
[]
array
LinkedList
function LinkedList() {
this.append = function(element){};
this.insert = function(position, element){};
this.removeAt = function(position){};
this.remove = function(element){};
this.indexOf = function(element){};
this.isEmpty = function() {};
this.size = function() {};
this.toString = function(){};
this.print = function(){};
}
LinkedList
append(element)
insert(position, element)
remove(element)
indexOf(element)
removeAt(position)
isEmpty() true
false
size()
length
toString() Node
toString
LinkedList
append
this.append = function(element){
} else {
//get last item and assign next to node to make the link
current.next = node; //{5}
}
Node element
{1}
null
{4}
current
{2}
current.next
null
{5}
Node null
{6}
LinkedList
remove
remove
this.removeAt = function(position){
length--; // {10}
return current.element;
} else {
return null; // {11}
}
};
{1} size - 1
null
head
current {2}
current
head current.next
{6}
previous.next
current.next {9}
https://developer.mozilla.org/en-US/docs/Web/JavaScrip
t/Memory_Management
{6} current
current.next null
previous previous.next
current current
previous.next current.next
current previous
current previous.next
current.next
insert
} else {
while (index++ < position){ //{3}
previous = current;
current = current.next;
}
node.next = current; //{4}
previous.next = node; //{5}
}
} else {
return false; //{6}
}
};
{1}
remove false
{6}
current
node.next current
head node.next current
head node {2}
{3}
current
previous
previous current
node {4}
previous current previous.next
node {5}
previous
current node.next current
previous.next node
node previous
current node.next current
previous.next node
previous
LinkedList
toString indexOf isEmpty size
toString LinkedList
toString
this.toString = function(){
head
current {1}
{2}
{3} current
null while
{4}
{5} {6}
indexOf indexOf
-1
this.indexOf = function(element){
return -1;
};
current head
index {1}
{2}
{3} {4}
{5}
current
= current.next null -1
remove
this.remove = function(element){
let index = this.indexOf(element);
return this.removeAt(index);
};
removeAt
indexOf
removeAt
removeAt
removeAt
isEmpty size
this.isEmpty = function() {
return length === 0;
};
this.size = function() {
return length;
};
size length
length LinkedList
getHead
this.getHead = function(){
return head;
};
head LinkedList
LinkedList
DoublyLinkedList
function DoublyLinkedList() {
this.element = element;
this.next = null;
this.prev = null; //NEW
};
let length = 0;
let head = null;
let tail = null; //NEW
//methods here
}
LinkedList
DoublyLinkedList NEW Node prev
DoublyLinkedList tail
next
next prev
} else {
while (index++ < position){ //{4}
previous = current;
current = current.next;
}
node.next = current; //{5}
previous.next = node;
return true;
} else {
return false;
}
};
current {3}
node.prev current current.next
null node node.next null
tail node
current
{4} current previous
node.next current {5} previous.next node
insert remove
position length/2
this.removeAt = function(position){
} else {
previous = current;
current = current.next;
}
length--;
return current.element;
} else {
return null;
}
};
current
{2}
tail
tail current {4}
tail current.prev
tail.prev tail
next null tail.next = null
{5}
current
previous.next current.next.prev
previous.next current.next current.next.prev
previous
tail.next
null head
CircularLinkedList
LinkedList DoublyLinkedList
Set
{}
Array
Set
Set
Set
function Set() {
let items = {};
}
items
Set
add(value)
delete(value)
has(value) true false
clear()
size()
length
values()
has(value)
add remove
this.has = function(value){
return value in items;
};
in
items
this.has = function(value){
return items.hasOwnProperty(value);
};
hasOwnProperty
add
this.add = function(value){
if (!this.has(value)){
items[value] = value; //{1}
return true;
}
return false;
};
value
value {1} true
false
remove
this.delete = function(value){
if (this.has(value)){
delete items[value]; //{2}
return true;
}
return false;
};
remove value
value {2} true
false
items delete
items {2}
Set
items console.log
clear
this.clear = function(){
items = {}; // {3}
};
items {3}
remove
size
length add
remove LinkedList
Object
this.size = function(){
return Object.keys(items).length; //{4}
};
Object keys
length
{4} items
items
this.sizeLegacy = function(){
let count = 0;
for(let key in items) { //{5}
if(items.hasOwnProperty(key)) //{6}
++count; //{7}
}
return count;
};
items {5}
Object
values
items
this.values = function(){
let values = [];
for (let i=0, keys=Object.keys(items); i<keys.length; i++) {
values.push(items[keys[i]]);
}
return values;
};
this.valuesLegacy = function(){
let values = [];
for(let key in items) { //{7}
if(items.hasOwnProperty(key)) { //{8}
values.push(items[key]);
}
}
return values;
};
items {7}
{8} sizeLegacy
Set
set.add(1);
console.log(set.values()); //outputs ["1"]
console.log(set.has(1)); //outputs true
console.log(set.size()); //outputs 1
set.add(2);
console.log(set.values()); //outputs ["1", "2"]
console.log(set.has(2)); //true
console.log(set.size()); //2
set.remove(1);
console.log(set.values()); //outputs ["2"]
set.remove(2);
console.log(set.values()); //outputs []
Set
this.union = function(otherSet){
let unionSet = new Set(); //{1}
return unionSet;
};
{1}
values Set
{2}
{3}
this.intersection = function(otherSet){
let intersectionSet = new Set(); //{1}
return intersectionSet;
}
intersection
Set Set Set
{1}
values Set {2}
otherSet {3} has
Set Set
intersectionSet {4}
["2", "3"] 2 3
difference Set
this.difference = function(otherSet){
let differenceSet = new Set(); //{1}
return differenceSet;
};
intersection values difference
{3}
otherSet {1} {2}
{4}
intersection
["1"] 1 setA
subset Set
this.subset = function(otherSet){
Set
otherSet
{3}
{2}
otherSet {3} otherSet
false {4}
otherSet {4} true {5}
console.log(setA.subset(setB));
console.log(setA.subset(setC));
Set Set
Set
https://developer.mozilla.org/en-US/docs/Web/JavaScript/R
eference/Global_Objects/Set http://goo.gl/2li2a5
Set
Set
set.delete(1);
clear set
Set Set
{1}
{2} {3}
intersection
intersection
setA setB
setA setB
difference
Set
Set
Set Set
Set Map
Map
Set
Dictionary
function Dictionary(){
var items = {};
}
Set Object
set(key,value)
delete(key)
has(key) true false
get(key)
clear()
size()
length
keys()
values()
has(key)
set remove
this.has = function(key){
return key in items;
};
Set
in key items
set
delete delete
Set key value
this.delete = function(key){
if (this.has(key)){
delete items[key];
return true;
}
return false;
};
remove key
items
this.get = function(key) {
return this.has(key) items[key] : undefined;
};
get
key undefined
undefined null
Chapter 1
values
values
this.values = function(){
var values = [];
for (var k in items) { //{1}
if (this.has(k)) {
values.push(items[k]); //{2}
}
}
return values;
};
items {1}
has key
values {2}
for-in
items has
items
Object
keys Dictionary
keys Object
Dictionary
this.keys = function(){
return Object.keys(items);
};
items
getItems items
this.getItems = function(){
return items;
}
Dictionary
dictionary
true
console.log(dictionary.has('Gandalf'));
console.log(dictionary.size());
console.log(dictionary.keys());
console.log(dictionary.values());
console.log(dictionary.get('Tyrion'));
dictionary.delete('John');
console.log(dictionary.keys());
console.log(dictionary.values());
console.log(dictionary.getItems());
dictionary
items
HashTable HashMap
Dictionary
get
function HashTable() {
var table = [];
}
put(key,value)
remove(key)
get(key)
hash HashTable
http://www.asciitable.com/
hash put
key hash
{5}
{6}
value position hash
{7}
HashTable get
key hash
table
remove
this.remove = function(key){
table[loseloseHashCode (key)] = undefined;
};
HashTable
hash undefined
HashTable table
ArrayList
undefined
hash
HashTable
HashTable
get
console.log(hash.get('Gandalf'));
console.log(hash.get('Loiane'));
Gandalf HashTable
hash.remove('Gandalf');
console.log(hash.get('Gandalf'));
hash.get('Gandalf') undefined
Gandalf
hash
HashTable
HashTable
helper print
HashTable
this.print = function () {
for (var i = 0; i < table.length; ++i) { //{1}
if (table[i] !== undefined) { //{2}
console.log(i + ": " + table[i]); //{3}
}
}
};
{1}
{2} {3}
hash.print();
HashTable
LinkedList
LinkedList
LinkedList
put
get remove
HashTable
helper LinkedList
ValuePair HashTable
put
{1}
LinkedList
Chapter 5 ValuePair key
value LinkedList append {2}
Chapter 5
get
this.get = function(key) {
var position = loseloseHashCode(key);
while(current.next){ //{5}
if (current.element.key === key){ //{6}
return current.element.value; //{7}
}
current = current.next; //{8}
}
{3} undefined
HashTable {10}
LinkedList
{4}
{5} current.next null
while {9}
HashTable
remove
LinkedList LinkedList
remove
this.remove = function(key){
var position = loseloseHashCode(key);
remove get
LinkedList
current {11}
remove LinkedList {12}
{13}
position undefined {14}
true
{15} false
HashTable {17}
{16} get
HashMap
put
hash {1}
position
undefined index position + 1
{4} ++
index {5}
index {6}
{7}
get
this.get = function(key) {
var position = loseloseHashCode(key);
{8}
undefined
{14}
{9} {10}
HashTable
{11}
{12} {13}
ValuePair HashTable
remove get
{10} {13}
table[index] = undefined;
undefined
hash {1}
5381 key {2}
hash 33
{3}
HashTable
djb2HashCode loseloseHashCode
http://goo.gl/VtdN2x
Map
Dictionary Map
Map
https://developer.mozilla.org/en-US/docs/Web/JavaScript/R
eference/Global_Objects/Map http://goo.gl/dm8VP6
Map
var map = new Map();
map.set('Gandalf', 'gandalf@email.com');
map.set('John', 'johnsnow@email.com');
map.set('Tyrion', 'tyrion@email.com');
delete
map.delete('John');
clear map
Dictionary
Set Map
WeakMap WeakSet
Map Set
WeakMap
WeakMap
{1} {2}
WeakSet
Map WeakMap WeakSet
tree
BinarySearchTree
function BinarySearchTree() {
Node
{1}
LinkedList Chapter 5
{2}
insert(key)
search(key) true
false
inOrderTraverse
preOrderTraverse
postOrderTraverse
min
max
remove(key)
Chapter 11
this.insert = function(key){
Node
{1}
left right null
{2}
helper {3}
insertNode
insertNode
{3}
{4}
{5} {6}
insertNode {7}
{8} {9}
insertNode
{10}
var tree = new BinarySearchTree();
tree.insert(11);
{2}
11
tree.insert(7);
tree.insert(15);
tree.insert(5);
tree.insert(3);
tree.insert(9);
tree.insert(8);
tree.insert(10);
tree.insert(13);
tree.insert(12);
tree.insert(14);
tree.insert(20);
tree.insert(18);
tree.insert(25);
tree.insert(6);
{3}
insertNode root key[6]
{4} key[6] < root[11] true
{5} node.left[7] null {7}
insertNode node.left[7] key[6]
insertNode
{4} key[6] < node[7] true
{5} node.left[5] null {7}
insertNode node.left[5] key[6]
insertNode {4}
key[6] < node[5] false {8} node.right
null
{9} 6
6
this.inOrderTraverse = function(callback){
inOrderTraverseNode(root, callback); //{1}
};
inOrderTraverse callback
http://en.wikipedia.org/wiki/Visitor_pattern
helper
node callback {1}
node
null
{2}
{3}
{4} callback
{5}
inOrderTraverse
this.preOrderTraverse = function(callback){
preOrderTraverseNode(root, callback);
};
preOrderTraverseNode
preOrderTraverse
this.postOrderTraverse = function(callback){
postOrderTraverseNode(root, callback);
};
postOrderTraverseNode
{1}
{2} {3}
postOrderTraverse
this.min = function() {
return minNode(root); //{1}
};
min minNode
{1}
return node.key;
}
return null; //{4}
};
minNode
minNode {1}
max
this.max = function() {
return maxNode(root);
};
return node.key;
}
return null;
};
{5}
this.search = function(key){
return searchNode(root, key); //{1}
};
} else {
return true; //{7}
}
};
search
helper {1}
searchNode
{1} root
node
null false
null
{3}
{4} {5}
{6}
true {7}
searchNode {1}
node[root[11]] null {2} {3}
key[1] < node[11] true {3} {4}
searchNode node[7] key[1]
node[7] null {2} {3}
key[1] < node[7] true {3} {4}
searchNode node[5] key[1]
node[5] null {2} {3}
key[1] < node[5] true {3} {4}
searchNode node[3] key[1]
node[3] null {2} {3}
key[1] < node[3] true {3} {4}
searchNode null key[1] null
node[3]
null
node null {2} node null
false
key removeNode
root key {1}
removeNode
removeNode
removeNode
{2} null
null
{3}
{4}
{6}
{7}
findMinNode
{9}
null {9}
null
null
null {11}
null
{4} {7}
{5} {8}
{12}
{13}
{14} {15}
{16}
{17}
{18}
{19}
{20}
{21}
findMinNode min
min
findMinNode
var insertNode = function(node, element) {
if (node === null) {
node = new Node(element);
} else if (element < node.key) {
node.left = insertNode(node.left, element);
}
} else if (element > node.key) {
node.right = insertNode(node.right, element);
}
}
return node;
};
{1} {2}
var heightNode = function(node) {
if (node === null) {
return -1;
} else {
return Math.max(heightNode(node.left),
heightNode(node.right)) + 1;
}
};
}
{1}
{2}
{3}
{1}
{2}
{3}
http://goo.gl/OxED8K
http://goo.gl/SFlhW6
function Graph() {
var vertices = []; //{1}
var adjList = new Dictionary(); //{2}
}
{1}
Chapter 7
{2}
vertices adjList
Graph
addVertex
this.addVertex = function(v){
vertices.push(v); //{3}
adjList.set(v, []); //{4}
};
v
{3}
v {4}
addEdge
v
w {5} w v
{5}
w v {6}
{4}
var graph = new Graph();
var myVertices = ['A','B','C','D','E','F','G','H','I']; //{7}
for (var i=0; i<myVertices.length; i++){ //{8}
graph.addVertex(myVertices[i]);
}
graph.addEdge('A', 'B'); //{9}
graph.addEdge('A', 'C');
graph.addEdge('A', 'D');
graph.addEdge('C', 'D');
graph.addEdge('C', 'G');
graph.addEdge('D', 'G');
graph.addEdge('D', 'H');
graph.addEdge('B', 'E');
graph.addEdge('B', 'F');
graph.addEdge('E', 'I');
{7} vertices
{8} {9}
toString Graph
this.toString = function(){
var s = '';
for (var i=0; i<vertices.length; i++){ //{10}
s += vertices[i] + ' -> ';
var neighbors = adjList.get(vertices[i]); //{11}
for (var j=0; j<neighbors.length; j++){ //{12}
s += neighbors[j] + ' ';
}
s += '\n'; //{13}
}
return s;
};
vertices {10}
{11} {12}
{13}
console.log(graph.toString());
A
B C D
Chapter 3
Chapter 4
var initializeColor = function(){
var color = [];
for (var i=0; i<vertices.length; i++){
color[vertices[i]] = 'white'; //{1}
}
return color;
};
bfs
enqueue {4}
{5}
{6} {7}
grey
u {9}
{10} white {11}
grey {12}
{13} dequeue
black {14}
bfs
Chapter 8
callback {15}
bfs
BFS
this.BFS = function(v){
while (!queue.isEmpty()){
var u = queue.dequeue(),
neighbors = adjList.get(u);
color[u] = 'grey';
for (i=0; i<neighbors.length; i++){
var w = neighbors[i];
if (color[w] === 'white'){
color[w] = 'grey';
d[w] = d[u] + 1; //{6}
pred[w] = u; //{7}
queue.enqueue(w);
}
}
color[u] = 'black';
}
return { //{8}
distances: d,
predecessors: pred
};
};
BFS
bfs bfs
BFS
d {1} pred
{2}
d {4} pred null {5}
{3}
w u w u
{7} {6} v w 1
u u w d[u]
d pred {8}
BFS
BFS A
A 1 B C D 2
E F G H 3 I
A {9}
A {10} A
toVertex vertices {11}
{12}
toVertex fromVertex {13} v
v {14}
{15}
s
{16}
{17}
s {18} {19}
A
this.dfs = function(callback){
var color = initializeColor(); //{1}
color {1}
white
{2} {3} Graph
dfsVisit color
callback {4}
u grey {5}
callback {6}
u {7}
white {10} {8} w {9} u dfsVisit
w {11} w
black {12}
dfs
graph.dfs(printNode);
{4}
dfsVisit A
B {4}
A
dfs
BFS
{1}
d f p {2}
{3}
{4}
{5}
u {6}
{7}
time
2|V|
u d[u] < f[u]
result
Chapter 11
this.dijkstra = function(src){
var dist = [], visited = [],
length = this.graph.length;
{1} dist
INF = Number.MAX_SAFE_INTEGER visited[] false
{2}
{3}
{4}
{5} visited
{6}
{7}
{8}
src
minDistance dist
Chapter 11
this.floydWarshall = function(){
var dist = [], length = this.graph.length, i, j, k;
{1}
i j
{2} 0...k
i j k
{3} i j
k {3}
{4}
{3}
INF i j
this.prim = function() {
var parent = [], key = [], visited = [];
length = this.graph.length, i;
key[0] = 0; //{1}
parent[0] = -1;
{1} keys
INF = Number.MAX_SAFE_INTEGER visited[] false
{2}
parent[0] = -1
{3}
{4}
{5} visited
{6}
parent {7} {8}
{9}
key
parent
while(ne<length-1) { //{2}
function ArrayList(){
ArrayList
{1} insert {2}
push Array
Chapter 2 toString {3}
join Array
join
ArrayList
this.bubbleSort = function(){
var length = array.length; //{1}
for (var i=0; i<length; i++){ //{2}
for (var j=0; j<length-1; j++ ){ //{3}
if (array[j] > array[j+1]){ //{4}
swap(array, j, j+1); //{5}
}
}
}
};
{3}
{4}
{5}
j+1 j
swap
ArrayList
{2}
{3}
{6} 5
[5, 4, 3, 2, 1]
ArrayList
{7}
console {8} {9}
console
{10}
ArrayList
4 5
{1}
this.modifiedBubbleSort = function(){
var length = array.length;
for (var i=0; i<length; i++){
for (var j=0; j<length-1-i; j++ ){ //{1}
if (array[j] > array[j+1]){
swap(j, j+1);
}
}
}
};
Chapter 12
this.selectionSort = function(){
var length = array.length, //{1}
indexMin;
for (var i=0; i<length-1; i++){ //{2}
indexMin = i; //{3}
for (var j=i; j<length; j++){ //{4}
if(array[indexMin]>array[j]){ //{5}
indexMin = j; //{6}
}
}
if (i !== indexMin){ //{7}
swap(i, indexMin);
}
}
};
{1}
{2}
min
{3}
i {4}
j {5}
{6}
{4}
{7}
array = createNonSortedArray(5);
console.log(array.toString());
array.selectionSort();
console.log(array.toString());
[5, 4, 3, 2, 1]
{4}
{2}
this.insertionSort = function(){
var length = array.length, //{1}
j, temp;
for (var i=1; i<length; i++){ //{2}
j = i; //{3}
temp = array[i]; //{4}
while (j>0 && array[j-1] > temp){ //{5}
array[j] = array[j-1]; //{6}
j--;
}
array[j] = temp; //{7}
}
};
{1}
{2}
i {3} {4}
{5}
{6} j
Array sort
Array.prototype.sort
Array.prototype.sort
this.mergeSort = function(){
array = mergeSortRec(array);
};
helper
mergeSort
mergeSort mergeSortRec
1 {1} 1 {2}
1
{3}
left {4} right {5}
left right
merge {6}
mergeSortRec
merge
{7}
left right
{8} left
right left
{9}
right
{10}
left {11}
right {12}
{13}
mergeSort
pivot
this.quickSort = function(){
quick(array, 0, array.length - 1);
};
index {1}
quick
index partition {3}
{2}
index {3}
{4} {5}
{6} {7}
pivot
{3}
swap
{7}
partition
this.heapSort = function(){
var heapSize = array.length;
buildHeap(array); //{1}
{1} array[parent(i)] ≥
array[i]
{2}
{2}
heapify
buildHeap
heapify
{2}
{3}
https://github.com/loiane/javascript-datastructures-algo
rithms
search BinarySearchTree
Chapter 8 indexOf LinkedList Chapter 5
this.sequentialSearch = function(item){
for (var i=0; i<array.length; i++){ //{1}
if (item === array[i]){ //{2}
return i; //{3}
}
}
return -1; //{4}
};
{1}
{2}
true {3}
{11}
BinarySearchTree Chapter 8
search
Chapter 8
function recursiveFunction(someParam){
recursiveFunction(someParam);
};
function recursiveFunction1(someParam){
recursiveFunction2(someParam);
};
function recursiveFunction2(someParam){
recursiveFunction1(someParam);
};
recursiveFunction
var i = 0;
function recursiveFn () {
i++;
recursiveFn();
}
try {
recursiveFn();
} catch (ex) {
alert('i = ' + i + ' error: ' + ex);
}
Chapter 10
function fibonacci(num){
if (num === 1 || num === 2){ //{1}
return 1;
}
}
{1}
function fibonacci(num){
if (num === 1 || num === 2){
return 1;
}
return fibonacci(num - 1) + fibonacci(num - 2);
}
function fib(num){
var n1 = 1,
n2 = 1,
n = 1;
for (var i = 3; i<=num; i++){
n = n1 + n2;
n1 = n2;
n2 = n;
}
return n;
}
Chapter 9
Chapter 9
function MinCoinChange(coins){
var coins = coins; //{1}
var cache = {}; //{2}
this.makeChange = function(amount) {
var me = this;
if (!amount) { //{3}
return [];
}
if (cache[amount]) { //{4}
return cache[amount];
}
var min = [], newMin, newAmount;
for (var i=0; i<coins.length; i++){ //{5}
var coin = coins[i];
newAmount = amount - coin; //{6}
if (newAmount >= 0){
newMin = me.makeChange(newAmount); //{7}
}
if (
newAmount >= 0 && //{8}
(newMin.length < min.length-1 || !min.length)//{9}
&& (newMin.length || !newAmount) //{10})
{
min = [coin].concat(newMin); //{11}
console.log('new Min ' + min + ' for ' + amount);
}
}
return (cache[amount] = min); //{12}
};
}
cache {2}
makeChange
amount < 0
{3}
cache {4}
coins
{5} newAmount {6}
cache
[1, 10, 25]
1 3 4
function knapSack(capacity, weights, values, n) {
var i, w, a, b, kS = [];
{3} i
{5}
{4}
{6}
kS
function findValues(n, capacity, kS, weights, values){
var i=n, k=capacity;
console.log('Items that are part of the solution:');
{7}
function lcs(wordX, wordY) {
var m = wordX.length,
n = wordY.length,
l = [],
i, j, a, b;
printSolution
var a = m, b = n, i, j,
x = solution[a][b],
answer = '';
{1}
m
7500
var s=[];
for (i = 0; i <= n; i++){
s[i] = [];
for (j=0; j<=n; j++){
s[i][j] = 0;
}
}
{2} matrixChainOrder
s[i][j]=k;
{3}
printOptimalParenthesis(s, 1, n-1);
printOptimalParenthesis
(A[1](A[2](A[3]A[4]))) (A(B(CD)))
Chapter 9
function MinCoinChange(coins){
var coins = coins; //{1}
this.makeChange = function(amount) {
var change = [],
total = 0;
for (var i=coins.length; i>=0; i--){ //{2}
var coin = coins[i];
while (total + coin <= amount) { //{3}
change.push(coin); //{4}
total += coin; //{5}
}
}
return change;
};
}
MinCoinChange
MinCoinChange
{1}
{2}
total total amount {3} coin
{4} total {5}
[25, 10, 1]
[1, 3, 4]
[4, 1, 1]
[3, 3]
function knapSack(capacity, values, weights) {
var n = values.length,
load = 0, i = 0, val = 0;
{1}
{2}
val load
{3}
r
var printArray = function(array){
for (var i=0; i<array.length; i++){
console.log(array[i]);
}
};
printArray([1, 2, 3, 4, 5]);
Math.min
...
map
var daysOfWeek = [
{name: 'Monday', value: 1},
{name: 'Tuesday', value: 2},
{name: 'Wednesday', value: 7}
];
filter
reduce
http://rea
ctivex.io/learnrx/
http://underscorejs.org/
http://bilby.brianmckenna.org/
http://danieltao.com/lazy.js/
https://baconjs.github.io/
http://eliperelman.com/fn.js/
http://functionaljs.com/
http://ramdajs.com/0.20.1/index.html
http://swannodette.github.io/mori/
https://www.pack
tpub.com/web-development/functional-programming-javascrip
t
Chapter 10
Chapter 10
function increment(num){
return ++num;
}
increment(1)
num
2
Chapter 10
{1}
-1 {1}
{1} -1
sequentialSearch
{1}
{1}
sequentialSearch
sequentialSearch
function bubbleSort(array){
var length = array.length;
for (var i=0; i<length; i++){ //{1}
for (var j=0; j<length-1; j++ ){ //{2}
if (array[j] > array[j+1]){
swap(array, j, j+1);
}
}
}
}
{1} {2}
function bubbleSort(array){
var length = array.length;
var cost = 0;
for (var i=0; i<length; i++){ //{1}
cost++;
for (var j=0; j<length-1; j++ ){ //{2}
cost++;
if (array[j] > array[j+1]){
swap(array, j, j+1);
}
}
}
console.log('cost for bubbleSort with input size ' + length + '
is ' + cost);
}
bubbleSort
bubbleSort
bigOChart chapter12
https://en.wikipe
dia.org/wiki/NP-completeness
http://goo.gl/gxIu9w
http://uva.onlinejudge.org/
http://www.spoj.com/
http://coderbyte.com/
https://projecteuler.net/
https://www.hackerrank.com
http://www.codechef.com/
http://www.topcoder.com/
https://github.com
71
53
193 46
125 68
184
195 30
195 30
193
187
283 188
189
30 189
30 187
40 184
41 187
185 186
60 190
62 63 185
64
65
66
64 33
63 32 33
61
61 32
62 63 32
62
62 63 274
185
46 100 86
47
48 275 276
47 279
48 276 278
53
274
247
248 249 123
30
166
167 168 30
166 30
282 30
30
199 200 30
201 202 203 126
201
203 204 205 199 207
206 210 211
207 208 209
225 226 212 213 214
226 227 228
228 229 144 145
140
270 143
121 140 141
96 97 98 142
126 142 143
144
284 141 142
284 143
141 142
284 143
284 142 143
60
60
252
31 253
31
31 8
167 192
217
230 218
49 274
52 258
49 267
49 268
145
269 149
270 151
274 146 147 148
274 148 149
271 149
269 145
243 244
274
191
31
27 28
269
172
196
7 284
10 231
231
197 198 233
232
195 169
195 8
195
196 57 58
199 200 58
59
192 58
194 59
195 59
194
215 266
267 268 56
266 267 57 58
57
13
284 22 23 24
284 20 21
282 17
125 20 21
16
159 160 15
149
272
273 113
271 111 112
272 113
111
107 113
111
7 100
8 260
28 29
26
27
167 26
26
258 145 159
259 260
257
221 141
221 222
264
265
263
274 262
261 233
262 263 234 235 236
74
266
155 267
158 255
156 157 158
159 218 219
221
100 101 219
102
274
101 53 55 56
103
105
108 109
110 7
105 106
108 12
111
192
185 254
181 254
180 181
182 284
183 284
281
41
281 282
283
283 88
282
123 93
91 92 93
29 88 89
28 29 90
90
41 90
43 91
42 89
44 91
17 236
18 237
18 238 239
19 239 242
19
20
19
20 274
250
174 175 252 253
173 174 251 252
191
219
219 220
94 95 246
96 247
96 246
255 175
254
254
176 177
180 181 224 225
177 179 225
246
69 243 244
69 70 231 233
69 70 233 234 235 236
70 236 237 238
229 230 231
229 195
230
231 284
284
184
184 78 79 80
151 74
153 77
153 78
154 76
246 78
76
129 75
77 78
129
129 133 134 74 75
129 131 132 75
129 134 135
129 130 131 84
84 85 86
123
125 30
126 30
124 134 135
126
125
127
128 252
252
206
206 214 284
206 284
206 215
206 217 213
127 212 213
164 194
165 283
166 283
166
166
128
171
172 173 41
174 175
173 174 15
16
164 192
168 169 170 171
53 72
54
72 30
30
274
11