diff --git a/.babelrc b/.babelrc
new file mode 100644
index 00000000..df4ad4d9
--- /dev/null
+++ b/.babelrc
@@ -0,0 +1,7 @@
+{
+ "presets": ["env"],
+ "plugins": [
+ "add-module-exports",
+ "transform-es2015-modules-umd"
+ ]
+}
diff --git a/.bithoundrc b/.bithoundrc
new file mode 100644
index 00000000..46722b1d
--- /dev/null
+++ b/.bithoundrc
@@ -0,0 +1,19 @@
+{
+ "ignore": [
+ "**/.vscode/**",
+ "**/node_modules/**",
+ "**/dist/**",
+ "**/examples/**"
+ ],
+ "test": [
+ "**/test/**"
+ ],
+ "critics": {
+ "lint": {
+ "engine": "eslint"
+ },
+ "wc": {
+ "limit": 1000
+ }
+ }
+}
diff --git a/.editorconfig b/.editorconfig
new file mode 100644
index 00000000..8b1709b6
--- /dev/null
+++ b/.editorconfig
@@ -0,0 +1,12 @@
+root = true
+
+[*]
+indent_style = space
+indent_size = 2
+end_of_line = LF
+charset = utf-8
+trim_trailing_whitespace = true
+insert_final_newline = true
+
+[*.md]
+trim_trailing_whitespace = false
\ No newline at end of file
diff --git a/.eslintrc.json b/.eslintrc.json
new file mode 100644
index 00000000..ac117e1a
--- /dev/null
+++ b/.eslintrc.json
@@ -0,0 +1,39 @@
+{
+ "env": {
+ "browser": true,
+ "commonjs": true,
+ "es6": true,
+ "node": true
+ },
+ "globals": {
+ "expect": true,
+ "it": true,
+ "describe": true,
+ "beforeEach": true,
+ "afterEach": true,
+ "document": false,
+ "navigator": false,
+ "window": false
+ },
+ "parser": "babel-eslint",
+ "extends": "airbnb-base",
+ "rules": {
+ "class-methods-use-this": 0,
+ "no-plusplus": 0,
+ "arrow-parens": 0,
+ "no-console": 0,
+ "import/prefer-default-export": 0,
+ "comma-dangle": 0,
+ "no-underscore-dangle": 0,
+ "no-param-reassign": 0,
+ "no-return-assign": 0,
+ "no-restricted-globals": 0,
+ "no-multi-assign": 0,
+ "prefer-destructuring": ["error", {"object": true, "array": false}],
+ "padded-blocks": 0,
+ "no-sparse-arrays": 0,
+ "array-bracket-spacing": 0,
+ "import/no-named-as-default": 0,
+ "implicit-arrow-linebreak": 0
+ }
+}
diff --git a/.firebaserc b/.firebaserc
new file mode 100644
index 00000000..d33152ab
--- /dev/null
+++ b/.firebaserc
@@ -0,0 +1,5 @@
+{
+ "projects": {
+ "default": "javascript-ds-algorithms-book"
+ }
+}
diff --git a/.gitignore b/.gitignore
index 2458e8b0..0c2aa12a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -2,3 +2,10 @@
*.log
node_modules
coverage
+.nyc_output
+coverage.lcov
+mochawesome-report/*
+dist/js/*
+dist-/*
+dist/ts/*
+snippet.js
diff --git a/.travis.yml b/.travis.yml
new file mode 100644
index 00000000..7def9b91
--- /dev/null
+++ b/.travis.yml
@@ -0,0 +1,16 @@
+language: node_js
+node_js:
+ - node
+before_script:
+ - npm install -g --silent firebase-tools
+install:
+ - npm install
+script:
+ - npm run go
+after_success:
+ - npm run coverage
+ - test $TRAVIS_BRANCH = "master" && test $TRAVIS_PULL_REQUEST = "false" && firebase deploy --token $FIREBASE_TOKEN --non-interactive
+notifications:
+ email:
+ on_failure: change
+ on_success: change
diff --git a/.vscode/launch.json b/.vscode/launch.json
new file mode 100644
index 00000000..8b53d61d
--- /dev/null
+++ b/.vscode/launch.json
@@ -0,0 +1,50 @@
+{
+ // Use IntelliSense to learn about possible attributes.
+ // Hover to view descriptions of existing attributes.
+ // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
+ "version": "0.2.0",
+ "configurations": [
+ {
+ "type": "chrome",
+ "request": "launch",
+ "name": "Chrome",
+ "url": "http://127.0.0.1:8887/examples",
+ "webRoot": "${workspaceRoot}"
+ },
+ {
+ "type": "node",
+ "request": "launch",
+ "name": "Mocha JS",
+ "program": "${workspaceRoot}/node_modules/mocha/bin/_mocha",
+ "args": [
+ "-u",
+ "tdd",
+ "--timeout",
+ "999999",
+ "--compilers",
+ "js:babel-core/register",
+ "--colors",
+ "${workspaceRoot}/test/js/**/*.spec.js"
+ ],
+ "internalConsoleOptions": "openOnSessionStart"
+ },
+ {
+ "type": "node",
+ "request": "launch",
+ "name": "Mocha TS",
+ "program": "${workspaceRoot}/node_modules/mocha/bin/_mocha",
+ "args": [
+ "-u",
+ "tdd",
+ "--timeout",
+ "999999",
+ "-r",
+ "ts-node/register",
+ "--colors",
+ "${workspaceRoot}/test/ts/**/**/*.spec.ts"
+ ],
+ "protocol": "auto",
+ "internalConsoleOptions": "openOnSessionStart"
+ }
+ ]
+}
diff --git a/.vscode/settings.json b/.vscode/settings.json
new file mode 100644
index 00000000..55712c19
--- /dev/null
+++ b/.vscode/settings.json
@@ -0,0 +1,3 @@
+{
+ "typescript.tsdk": "node_modules/typescript/lib"
+}
\ No newline at end of file
diff --git a/.vscode/tasks.json b/.vscode/tasks.json
new file mode 100644
index 00000000..9b4e4d2c
--- /dev/null
+++ b/.vscode/tasks.json
@@ -0,0 +1,23 @@
+{
+ // See https://go.microsoft.com/fwlink/?LinkId=733558
+ // for the documentation about the tasks.json format
+ "version": "2.0.0",
+ "tasks": [
+ {
+ "type": "npm",
+ "script": "go",
+ "group": {
+ "kind": "build",
+ "isDefault": true
+ }
+ },
+ {
+ "type": "npm",
+ "script": "dev",
+ "group": {
+ "kind": "test",
+ "isDefault": true
+ }
+ }
+ ]
+}
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 00000000..ade741a9
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,7 @@
+# Change Log
+All notable changes to the "javascript-datastructures-algorithms" third edition source code bundle will be documented in this file.
+
+Based on [Keep a Changelog](http://keepachangelog.com/).
+
+## [Unreleased]
+- Initial release
diff --git a/README.md b/README.md
index 64771d99..96845564 100644
--- a/README.md
+++ b/README.md
@@ -1,12 +1,89 @@
Learning JavaScript Data Structures and Algorithms
====================================
-Source code of **Learning JavaScript Data Structures and Algorithms** book.
+[](https://travis-ci.org/loiane/javascript-datastructures-algorithms)
+[](https://codecov.io/gh/loiane/javascript-datastructures-algorithms)
+[](https://david-dm.org/loiane/javascript-datastructures-algorithms?type=dev)
+[](https://david-dm.org/loiane/javascript-datastructures-algorithms)
+[](https://greenkeeper.io/)
-| 1st edition | 2nd edition |
-| ------------- |:-------------:|
-|  |  |
-| [Book link](http://amzn.to/1Y1OWPx)| [Book link](http://amzn.to/1TSkcA1)|
+
+Source code of **Learning JavaScript Data Structures and Algorithms** book, third edition.
+
+## List of available chapters:
+
+* 01: [JavaScript: a quick overview](https://github.com/loiane/javascript-datastructures-algorithms/tree/third-edition/examples/chapter01_02)
+* 02: [ECMAScript and TypeScript Introduction](https://github.com/loiane/javascript-datastructures-algorithms/tree/third-edition/examples/chapter01_02)
+* 03: [Arrays](https://github.com/loiane/javascript-datastructures-algorithms/tree/third-edition/examples/chapter03)
+* 04: [Stacks](https://github.com/loiane/javascript-datastructures-algorithms/tree/third-edition/examples/chapter04)
+* 05: [Queues and Deques](https://github.com/loiane/javascript-datastructures-algorithms/tree/third-edition/examples/chapter05)
+* 06: [LinkedLists](https://github.com/loiane/javascript-datastructures-algorithms/tree/third-edition/examples/chapter06)
+* 07: [Sets](https://github.com/loiane/javascript-datastructures-algorithms/tree/third-edition/examples/chapter07)
+* 08: [Dictionaries and Hashes](https://github.com/loiane/javascript-datastructures-algorithms/tree/third-edition/examples/chapter08)
+* 09: [Recursion](https://github.com/loiane/javascript-datastructures-algorithms/tree/third-edition/examples/chapter09)
+* 10: [Trees](https://github.com/loiane/javascript-datastructures-algorithms/tree/third-edition/examples/chapter10)
+* 11: [Heap](https://github.com/loiane/javascript-datastructures-algorithms/tree/third-edition/examples/chapter11)
+* 12: [Graphs](https://github.com/loiane/javascript-datastructures-algorithms/tree/third-edition/examples/chapter12)
+* 13: [Sorting and Searching Algorithms](https://github.com/loiane/javascript-datastructures-algorithms/tree/third-edition/examples/chapter13)
+* 14: [Algorithm Design and Techniques](https://github.com/loiane/javascript-datastructures-algorithms/tree/third-edition/examples/chapter14)
+* 15: [Algorithm Complexity](https://github.com/loiane/javascript-datastructures-algorithms/tree/third-edition/examples/chapter15)
+
+### Third Edition Updates
+
+* Algorithms using ES2015+ (ES6+)
+* New data structures and algorithms
+* All chapters rewritten and reviewed
+* Three (3) new chapters
+* Creation of a Data Structures and Algorithms library that can be used in the browser or with Node.js
+* Algorithms tested with Mocha + Chai (test code available in `test` directory)
+* **TypeScript** version of the source code included (library and tests)
+
+## Project Structure
+
+`src/js/index.js` file contains all the data structures and algorithms listed by chapter.
+
+```
+|_examples (how to use each data structure and algorithm, organized by chapter)
+|_src
+|___js (source code: JavaScript version)
+|_____data-structures
+|_______models (classes used by DS: Node, ValuePair, ...)
+|_____others (other algorithms such as palindome checker, hanoi tower)
+|___ts (source code: TypeScript version)
+|_____data-structures
+|_______models
+|_____others
+|_test (unit tests with Mocha and Chai for src)
+|___js (tests for JavaScript code)
+|___ts (tests for TypeScript code)
+```
+
+## Installing and running the book examples With Node
+
+* Install [Node](https://nodejs.org)
+* Open terminal/cmd and change directory to this project folder: `cd /Users/.../javascript-datastructures-algorithms` (Linux/Max) or `cd C:/.../javascript-datastructures-algorithms`
+* run `npm install` to install all dependencies
+* To see the examples, run `http-server html` or `npm run serve`. Open your browser `http:\\localhost:8080` to see the book examples
+* Or `cd html/chapter01` and run each javascript file with node: `node 02-Variables`
+
+## Running the examples in the browser
+
+* Right click on the html file you would like to see the examples, right click and 'Open with Chrome (or any other browser)'
+
+* Or open the `examples/index.html` file to easily navigate through all examples:
+
+* Demo: [https://javascript-ds-algorithms-book.firebaseapp.com](https://javascript-ds-algorithms-book.firebaseapp.com)
+
+
+
+Happy Coding!
+
+## Other editions
+
+| 1st edition | 2nd edition | 3rd edition |
+| ------------- |:-------------:|:-------------:|
+|  |  |  |
+| [Book link](http://amzn.to/1Y1OWPx)| [Book link](http://amzn.to/1TSkcA1)| [Book link](http://a.co/cbMlYmJ)|
Book link - first edition:
- [Packt](https://www.packtpub.com/application-development/learning-javascript-data-structures-and-algorithms)
@@ -17,26 +94,14 @@ Book link - first edition:
Book link - second edition:
- [Packt](https://www.packtpub.com/web-development/learning-javascript-data-structures-and-algorithms-second-edition)
- [Amazon](http://amzn.to/1TSkcA1)
+ - [Chinese version](http://www.ituring.com.cn/book/2029)
- [Brazilian Portuguese version](https://novatec.com.br/livros/estruturas-de-dados-algoritmos-em-javascript/)
-### List of Chapters:
-
-* 01: [JavaScript: a quick overview](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter01)
-* 02: [Arrays](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter02)
-* 03: [Stacks](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter03)
-* 04: [Queues](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter04)
-* 05: [Linked Lists](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter05)
-* 06: [Sets](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter06)
-* 07: [Dictionaries and Hashes](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter07)
-* 08: [Trees](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter08)
-* 09: [Graphs](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter09)
-* 10: [Sorting and searching algorithms](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter10)
-* 11: [Pattern of algorithms](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter11)
-* 12: [Algorithm Complexity](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter12)
-
-### First Edition source code:
-
-Please refer to [this link](https://github.com/loiane/javascript-datastructures-algorithms/tree/master)
+ Book link - third edition:
+ - [Packt](https://www.packtpub.com/web-development/learning-javascript-data-structures-and-algorithms-third-edition)
+ - [Amazon](http://a.co/cbMlYmJ)
+ - [Chinese version](http://www.ituring.com.cn/book/2653)
+ - [Brazilian Portuguese version](https://novatec.com.br/livros/estruturas-de-dados-algoritmos-em-javascript-2ed/)
### Found an issue or have a question?
diff --git a/chapter01/01-HelloWorld.js b/chapter01/01-HelloWorld.js
deleted file mode 100755
index 89833849..00000000
--- a/chapter01/01-HelloWorld.js
+++ /dev/null
@@ -1,8 +0,0 @@
-function output(t) {
- document.write('
' + t + '
');
- return;
-}
-
-alert('Hello, World!');
-console.log('Hello, World!');
-output('Hello, World!');
\ No newline at end of file
diff --git a/chapter01/02-Variables.js b/chapter01/02-Variables.js
deleted file mode 100644
index 2920e5be..00000000
--- a/chapter01/02-Variables.js
+++ /dev/null
@@ -1,37 +0,0 @@
-var num = 1; //{1}
-num = 3; //{2}
-
-var price = 1.5; //{3}
-var name = 'Packt'; //{4}
-var trueValue = true; //{5}
-var nullVar = null; //{6}
-var und; //7
-
-console.log("num: "+ num);
-console.log("name: "+ name);
-console.log("trueValue: "+ trueValue);
-console.log("price: "+ price);
-console.log("nullVar: "+ nullVar);
-console.log("und: "+ und);
-
-//******* Variable Scope
-
-var myVariable = 'global';
-myOtherVariable = 'global';
-
-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}
\ No newline at end of file
diff --git a/chapter01/04-TruthyFalsy.js b/chapter01/04-TruthyFalsy.js
deleted file mode 100755
index d700cd2c..00000000
--- a/chapter01/04-TruthyFalsy.js
+++ /dev/null
@@ -1,23 +0,0 @@
-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)
-
-testTruthy({}); //true (object is always true)
-
-var obj = {name:'John'};
-testTruthy(obj); //true
-testTruthy(obj.name); //true
-testTruthy(obj.age); //age (prop does not exist)
\ No newline at end of file
diff --git a/chapter01/05-EqualsOperators.js b/chapter01/05-EqualsOperators.js
deleted file mode 100755
index 253c21b9..00000000
--- a/chapter01/05-EqualsOperators.js
+++ /dev/null
@@ -1,36 +0,0 @@
-//Packt == true
-
-console.log('packt' ? true : false);
-//outputs true
-
-console.log('packt' == true);
-//1 - converts Boolean using toNumber
-//'packt' == 1
-//2 - converts String using toNumber
-//NaN == 1
-//outputs false
-
-console.log('packt' == false);
-//1 - converts Boolean using toNumber
-//'packt' == 0
-//2 - converts String using toNumber
-//NaN == 0
-//outputs false
-
-console.log([0] == true);
-//1 - converts Boolean using toNumber
-//[0] == 1
-//2 - converts Object using toPrimitive
-//2.1 - [0].valueOf() is not primitive
-//2.2 - [0].toString is 0
-//0 == 1
-//outputs false
-
-//******************************* ===
-console.log('packt' === true); //false
-
-console.log('packt' === 'packt'); //true
-
-var person1 = {name:'John'};
-var person2 = {name:'John'};
-console.log(person1 === person2); //false, different objects
\ No newline at end of file
diff --git a/chapter01/06-ConditionalStatements.js b/chapter01/06-ConditionalStatements.js
deleted file mode 100755
index c7256c80..00000000
--- a/chapter01/06-ConditionalStatements.js
+++ /dev/null
@@ -1,51 +0,0 @@
-/* Example 01 - if */
-var num = 1;
-if (num === 1) {
- console.log("num is equal to 1");
-}
-
-/* Example 02 - if-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);
-}
-
-/* Example 03 - 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");
-}
-
-/* Example 04 - 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");
-}
-
-/* Example 05 - ternary operator - if..else */
-if (num === 1){
- num--;
-} else {
- num++;
-}
-
-//is the same as
-(num === 1) ? num-- : num++;
\ No newline at end of file
diff --git a/chapter01/10-ObjectOrientedJS.js b/chapter01/10-ObjectOrientedJS.js
deleted file mode 100644
index c67a6c78..00000000
--- a/chapter01/10-ObjectOrientedJS.js
+++ /dev/null
@@ -1,42 +0,0 @@
-/* Object example 1 */
-
-var obj = new Object();
-
-/* Object example 2 */
-
-var obj = {};
-
-obj = {
- name: {
- first: 'Gandalf',
- last: 'the Grey'
- },
- address: 'Middle Earth'
-};
-
-/* Object example 3 */
-
-function Book(title, pages, isbn){
- this.title = title;
- this.pages = pages;
- this.isbn = isbn;
- this.printIsbn = function(){
- console.log(this.isbn);
- }
-}
-
-var book = new Book('title', 'pag', 'isbn');
-
-console.log(book.title); //outputs the book title
-
-book.title = 'new title'; //update the value of the book title
-
-console.log(book.title); //outputs the updated value
-
-Book.prototype.printTitle = function(){
- console.log(this.title);
-};
-
-book.printTitle();
-
-book.printIsbn();
\ No newline at end of file
diff --git a/chapter01/11-ES6letconst.js b/chapter01/11-ES6letconst.js
deleted file mode 100644
index 6be49b70..00000000
--- a/chapter01/11-ES6letconst.js
+++ /dev/null
@@ -1,47 +0,0 @@
-//******* EcmaScript 6: let and const keywords
-// EcmaScript 6 Constants
-const PI = 3.141593;
-//PI = 3.0; //throws error
-console.log(PI);
-
-//******* EcmaScript 6: let is the new var
-var framework = 'Angular';
-var framework = 'React';
-console.log(framework);
-
-let language = 'JavaScript!';
-//let language = 'Ruby!'; //throws error
-console.log(language);
-
-//******* EcmaScript 6: variables scope
-let movie = 'Lord of the Rings';
-//var movie = 'Batman v Superman'; //throws error, variable movie already declared
-
-function starWarsFan(){
- let movie = 'Star Wars';
- return movie;
-}
-
-function marvelFan(){
- movie = 'The Avengers';
- return movie;
-}
-
-function blizzardFan(){
- let isFan = true;
- let phrase = 'Warcraft';
- console.log('Before if: ' + phrase);
- if (isFan){
- let phrase = 'initial text';
- phrase = 'For the Horde!';
- console.log('Inside if: ' + phrase);
- }
- phrase = 'For the Alliance!';
- console.log('After if: ' + phrase);
-}
-
-console.log(movie);
-console.log(starWarsFan());
-console.log(marvelFan());
-console.log(movie);
-blizzardFan();
\ No newline at end of file
diff --git a/chapter01/12-Es6StringTemplates.js b/chapter01/12-Es6StringTemplates.js
deleted file mode 100644
index 30dc62c1..00000000
--- a/chapter01/12-Es6StringTemplates.js
+++ /dev/null
@@ -1,7 +0,0 @@
-// Template literals
-var book = {
- name: 'Learning JavaScript DataStructures and Algorithms'
-};
-
-console.log(`You are reading ${book.name}.,
- and this is a new line`);
\ No newline at end of file
diff --git a/chapter01/13-ES6ArrowFunctions.js b/chapter01/13-ES6ArrowFunctions.js
deleted file mode 100644
index 317d576f..00000000
--- a/chapter01/13-ES6ArrowFunctions.js
+++ /dev/null
@@ -1,10 +0,0 @@
-//ES6: arrow functions
-let circleArea = (r) => {
- const PI = 3.14;
- let area = PI * r * r;
- return area;
-}
-console.log(circleArea(2));
-
-let circleArea2 = (r) => 3.14 * r * r;
-console.log(circleArea2(2));
\ No newline at end of file
diff --git a/chapter01/14-ES6ParameterHandling.js b/chapter01/14-ES6ParameterHandling.js
deleted file mode 100644
index af23585c..00000000
--- a/chapter01/14-ES6ParameterHandling.js
+++ /dev/null
@@ -1,37 +0,0 @@
-//******* EcmaScript 6: Default Parameter Values
-function sum (x = 1, y = 2, z = 3) {
- return x + y + z
-};
-console.log(sum(4,2)); //outpus 9
-
-//function above is the same as
-function sum2 (x, y, z) {
- if (x === undefined)
- x = 1;
- if (y === undefined)
- y = 2;
- if (z === undefined)
- z = 3;
- return x + y + z;
-};
-console.log(sum2(4,2)); //outpus 9
-
-//******* EcmaScript 6: spread operator ('...')
-var params = [3, 4, 5];
-console.log(sum(...params));
-
-var numbers = [1, 2, ...params]; //pushing values into array
-console.log(numbers);
-
-//******* EcmaScript 6: rest parameter ('...')
-function restParamaterFunction (x, y, ...a) {
- return (x + y) * a.length;
-}
-console.log(restParamaterFunction(1, 2, "hello", true, 7)); // outputs 9;
-
-//code above is the same as ES5:
-function restParamaterFunction2 (x, y) {
- var a = Array.prototype.slice.call(arguments, 2);
- return (x + y) * a.length;
-};
-console.log(restParamaterFunction2(1, 2, "hello", true, 7));
diff --git a/chapter01/15-ES6EnhancedObjectProperties.js b/chapter01/15-ES6EnhancedObjectProperties.js
deleted file mode 100644
index 5f1dd9f1..00000000
--- a/chapter01/15-ES6EnhancedObjectProperties.js
+++ /dev/null
@@ -1,34 +0,0 @@
-// Destructuring Assignment + Property Shorthand
-var [x, y] = ['a', 'b'];
-var obj = { x, y };
-console.log(obj); // { x: "a", y: "b" }
-
-[x, y] = [y, x];
-var temp = x;
-x = y;
-y = temp;
-
-//code above is the same as
-var x = 'a';
-var y = 'b';
-var obj2 = { x: x, y: y };
-console.log(obj2); // { x: "a", y: "b" }
-
-
-// Method Properties
-var hello = {
- name : 'abcdef',
- printHello(){
- console.log('Hello');
- }
-}
-console.log(hello.printHello());
-
-//code above is the same as:
-var hello2 = {
- name: 'abcdef',
- printHello: function printHello() {
- console.log('Hello');
- }
-};
-console.log(hello2.printHello());
\ No newline at end of file
diff --git a/chapter01/16-ES6Classes.js b/chapter01/16-ES6Classes.js
deleted file mode 100644
index 2ec073d9..00000000
--- a/chapter01/16-ES6Classes.js
+++ /dev/null
@@ -1,88 +0,0 @@
-// ES6 classes
-class Book {
- constructor (title, pages, isbn) {
- this.title = title;
- this.pages = pages;
- this.isbn = isbn;
- }
- printIsbn(){
- console.log(this.isbn);
- }
-}
-
-let book = new Book('title', 'pag', 'isbn');
-
-console.log(book.title); //outputs the book title
-
-book.title = 'new title'; //update the value of the book title
-
-console.log(book.title); //outputs the book title
-
-
-//inheritance
-class ITBook extends Book {
-
- constructor (title, pages, isbn, technology) {
- super(title, pages, isbn);
- this.technology = technology;
- }
-
- printTechnology(){
- console.log(this.technology);
- }
-}
-
-let jsBook = new ITBook('Learning JS Algorithms', '200', '1234567890', 'JavaScript');
-
-console.log(jsBook.title);
-console.log(jsBook.printTechnology());
-
-//getter and setters
-class Person {
-
- constructor (name) {
- this._name = name;
- }
-
- get name() {
- return this._name;
- }
-
- set name(value) {
- this._name = value;
- }
-}
-
-let lotrChar = new Person('Frodo');
-console.log(lotrChar.name);
-lotrChar.name = 'Gandalf';
-console.log(lotrChar.name);
-
-lotrChar._name = 'Sam';
-console.log(lotrChar.name);
-
-
-//using symbols for private atributes
-
-var _name = Symbol();
-class Person2 {
-
- constructor (name) {
- this[_name] = name;
- }
-
- get name() {
- return this[_name];
- }
-
- set name(value) {
- this[_name] = value;
- }
-}
-
-let lotrChar2 = new Person2('Frodo');
-console.log(lotrChar2.name);
-lotrChar2.name = 'Gandalf';
-console.log(lotrChar2.name);
-
-console.log(Object.getOwnPropertySymbols(lotrChar2));
\ No newline at end of file
diff --git a/chapter02/01-Introduction.js b/chapter02/01-Introduction.js
deleted file mode 100755
index 93d80a8d..00000000
--- a/chapter02/01-Introduction.js
+++ /dev/null
@@ -1,12 +0,0 @@
-var averageTempJan = 31.9;
-var averageTempFeb = 35.3;
-var averageTempMar = 42.4;
-var averageTempApr = 52;
-var averageTempMay = 60.8;
-
-var averageTemp = [];
-averageTemp[0] = 31.9;
-averageTemp[1] = 35.3;
-averageTemp[2] = 42.4;
-averageTemp[3] = 52;
-averageTemp[4] = 60.8;
diff --git a/chapter02/02-CreatingAndInitialingArrays.js b/chapter02/02-CreatingAndInitialingArrays.js
deleted file mode 100755
index 1b20431e..00000000
--- a/chapter02/02-CreatingAndInitialingArrays.js
+++ /dev/null
@@ -1,34 +0,0 @@
-var daysOfWeek = [];
-
-var daysOfWeek = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
-
-var daysOfWeek = new Array(); //{1}
-
-var daysOfWeek = new Array(7); //{2}
-
-console.log(daysOfWeek.length);
-
-var daysOfWeek = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'); //{3}
-
-for (var i=0; i=0; i--){
- numbers[i] = numbers[i-1];
-}
-
-numbers[0] = -1;
-
-//printArray(numbers);
-
-//using method unshift
-numbers.unshift(-2);
-
-//printArray(numbers);
-
-numbers.unshift(-4, -3);
-
-//printArray(numbers);
-
-//**** Removing elements
-
-numbers.pop();
-
-//remove first position manually
-/*for (var i=0; i b) {
- return 1;
- }
- // a must be equal to b
- return 0;
-}
-
-console.log(numbers.sort(compare));
-
-//Sorting objects
-
-var friends = [
- {name: 'John', age: 30},
- {name: 'Ana', age: 20},
- {name: 'Chris', age: 25}
-];
-
-function comparePerson(a, b){
- if (a.age < b.age){
- return -1
- }
- if (a.age > b.age){
- return 1
- }
- return 0;
-}
-
-console.log(friends.sort(comparePerson));
-
-var names =['Ana', 'ana', 'john', 'John'];
-console.log(names.sort());
-
-console.log(names.sort(function(a, b){
- if (a.toLowerCase() < b.toLowerCase()){
- return -1
- }
- if (a.toLowerCase() > b.toLowerCase()){
- return 1
- }
- return 0;
-}));
-
-var names2 = ['Maève', 'Maeve'];
-console.log(names2.sort(function(a, b){
- return a.localeCompare(b);
-}));
-
-//*** toString
-console.log(numbers.toString());
-
-console.log(numbers.indexOf(10));
-console.log(numbers.indexOf(100));
-
-numbers.push(10);
-console.log(numbers.lastIndexOf(10));
-console.log(numbers.lastIndexOf(100));
-
-var numbersString = numbers.join('-');
-console.log(numbersString);
\ No newline at end of file
diff --git a/chapter02/06-ES6Methods.html b/chapter02/06-ES6Methods.html
deleted file mode 100644
index fdbeda65..00000000
--- a/chapter02/06-ES6Methods.html
+++ /dev/null
@@ -1,10 +0,0 @@
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/chapter02/06-ES6Methods.js b/chapter02/06-ES6Methods.js
deleted file mode 100644
index bf4eb36a..00000000
--- a/chapter02/06-ES6Methods.js
+++ /dev/null
@@ -1,112 +0,0 @@
-let numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
-
-//********** forEch using arrow functions
-console.log('forEach using arrow functions');
-
-numbers.forEach(x => {
- console.log((x % 2 == 0));
-});
-
-//********** using for..of loop
-console.log('using for..of loop');
-
-for (let n of numbers) {
- console.log((n % 2 == 0) ? 'even' : 'odd');
-}
-
-//********** Using the new ES6 iterator (@@iterator)
-console.log('Using the new ES6 iterator (@@iterator)');
-
-let iterator = numbers[Symbol.iterator]();
-console.log(iterator.next().value); //1
-console.log(iterator.next().value); //2
-console.log(iterator.next().value); //3
-console.log(iterator.next().value); //4
-console.log(iterator.next().value); //5
-
-//********** Array entries, keys and values
-console.log('Array entries, keys and values');
-
-console.log('Array.entries');
-let aEntries = numbers.entries(); //retrieve iterator of key/value
-console.log(aEntries.next().value); // [0, 1] - position 0, value 1
-console.log(aEntries.next().value); // [1, 2] - position 1, value 2
-console.log(aEntries.next().value); // [2, 3] - position 2, value 3
-
-console.log('Array.keys');
-let aKeys = numbers.keys(); //retrieve iterator of keys
-console.log(aKeys.next()); // {value: 0, done: false } done false means iterator has more values
-console.log(aKeys.next()); // {value: 1, done: false }
-console.log(aKeys.next()); // {value: 2, done: false }
-
-console.log('Array.values');
-let aValues = numbers.values();
-console.log(aValues.next()); // {value: 1, done: false } done false means iterator has more values
-console.log(aValues.next()); // {value: 2, done: false }
-console.log(aValues.next()); // {value: 3, done: false }
-
-//********** Using the from method
-console.log('Using the from method');
-
-let evens = Array.from(numbers, x => (x % 2 == 0));
-console.log(evens);
-
-let numbers2 = Array.from(numbers);
-console.log(numbers2);
-
-//********** Using Array.of
-console.log('Using Array.of');
-
-let numbers3 = Array.of(1);
-let numbers4 = Array.of(1,2,3,4,5,6);
-let numbersCopy = Array.of(...numbers4);
-console.log(numbers3);
-console.log(numbers4);
-console.log(numbersCopy);
-
-//********** Using the fill method
-console.log('Using the fill method');
-
-numbersCopy.fill(0);
-console.log(numbersCopy);
-
-numbersCopy.fill(2, 1);
-console.log(numbersCopy);
-
-numbersCopy.fill(1, 3, 5);
-console.log(numbersCopy);
-
-let ones = Array(6).fill(1);
-console.log(ones);
-
-//********** Using the copyWithin method
-console.log('Using the copyWithin method');
-
-let copyArray = [1, 2, 3, 4, 5, 6];
-console.log(copyArray);
-
-copyArray = copyArray.copyWithin(0, 3); //pos 3 value is copied to pos 0
-console.log(copyArray);
-
-copyArray = [1, 2, 3, 4, 5, 6];
-copyArray = copyArray.copyWithin(1, 3, 5); //pos 3-4 values are copied to pos 1-2
-console.log(copyArray);
-
-//********** methods find and findIndex
-console.log('methods find and findIndex');
-
-function multipleOf13(element, index, array) {
- return (element % 13 == 0) ? true : false;
-}
-
-console.log(numbers.find(multipleOf13));
-console.log(numbers.findIndex(multipleOf13));
-
-//********** EcmaScript 7: using the method includes
-console.log('EcmaScript 7: using the method includes');
-
-console.log(numbers.includes(15));
-console.log(numbers.includes(20));
-
-let numbers5 = [7,6,5,4,3,2,1];
-console.log(numbers5.includes(4,5));
diff --git a/chapter02/07-TypedArrays.js b/chapter02/07-TypedArrays.js
deleted file mode 100644
index 66a5b29a..00000000
--- a/chapter02/07-TypedArrays.js
+++ /dev/null
@@ -1,26 +0,0 @@
-let length = 5;
-let int16 = new Int16Array(length);
-
-let array16 = [];
-array16.length = length;
-
-for (let i=0; i
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/chapter03/02-UsingStacks.js b/chapter03/02-UsingStacks.js
deleted file mode 100644
index 9876e892..00000000
--- a/chapter03/02-UsingStacks.js
+++ /dev/null
@@ -1,24 +0,0 @@
-let stack = new Stack3();
- console.log(stack.isEmpty()); //outputs true
- stack.push(5);
- stack.push(8);
- console.log(stack.peek()); // outputs 8
- stack.push(11);
- console.log(stack.size()); // outputs 3
- console.log(stack.isEmpty()); //outputs false
- stack.push(15);
- stack.pop();
- stack.pop();
- console.log(stack.size()); // outputs 2
- stack.print(); // outputs [5, 8]
-
-
-//how to ensure true privacy
-//in case using Stack 2 uncomment code below
-/*let objectSymbols = Object.getOwnPropertySymbols(stack);
-
- console.log(objectSymbols.length); // 1
- console.log(objectSymbols); // [Symbol()]
- console.log(objectSymbols[0]); // Symbol()
- stack[objectSymbols[0]].push(1);
- stack.print(); //5, 8, 1*/
\ No newline at end of file
diff --git a/chapter03/03-BalancedSymbols.html b/chapter03/03-BalancedSymbols.html
deleted file mode 100755
index d347fe2e..00000000
--- a/chapter03/03-BalancedSymbols.html
+++ /dev/null
@@ -1,11 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/chapter03/03-BalancedSymbols.js b/chapter03/03-BalancedSymbols.js
deleted file mode 100644
index 0d4df4c6..00000000
--- a/chapter03/03-BalancedSymbols.js
+++ /dev/null
@@ -1,41 +0,0 @@
-function parenthesesChecker(symbols){
-
- let stack = new Stack(),
- balanced = true,
- index = 0,
- symbol, top,
- opens = "([{",
- closers = ")]}";
-
- while (index < symbols.length && balanced){
- symbol = symbols.charAt(index);
- if (opens.indexOf(symbol) >= 0){
- stack.push(symbol);
- console.log(`open symbol - stacking ${symbol}`);
- } else {
- console.log(`close symbol ${symbol}`);
- if (stack.isEmpty()){
- balanced = false;
- console.log('Stack is empty, no more symbols to pop and compare');
- } else {
- top = stack.pop();
- //if (!matches(top, symbol)){
- if (!(opens.indexOf(top) === closers.indexOf(symbol))) {
- balanced = false;
- console.log(`poping symbol ${top} - is not a match compared to ${symbol}`);
- } else {
- console.log(`poping symbol ${top} - is is a match compared to ${symbol}`);
- }
- }
- }
- index++;
- }
- if (balanced && stack.isEmpty()){
- return true;
- }
- return false;
-}
-
-console.log(parenthesesChecker('{([])}')); //true
-console.log(parenthesesChecker('{{([][])}()}')); //true
-console.log(parenthesesChecker('[{()]')); //false
\ No newline at end of file
diff --git a/chapter03/04-DecimalToBinary.html b/chapter03/04-DecimalToBinary.html
deleted file mode 100755
index a178b773..00000000
--- a/chapter03/04-DecimalToBinary.html
+++ /dev/null
@@ -1,11 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/chapter03/04-DecimalToBinary.js b/chapter03/04-DecimalToBinary.js
deleted file mode 100755
index d4695b51..00000000
--- a/chapter03/04-DecimalToBinary.js
+++ /dev/null
@@ -1,52 +0,0 @@
-//233 == 11101001
-//2x(10x10) + 3x(10) + 3x(1)
-
-function divideBy2(decNumber){
-
- var remStack = new Stack(),
- rem,
- binaryString = '';
-
- while (decNumber > 0){
- rem = Math.floor(decNumber % 2);
- remStack.push(rem);
- decNumber = Math.floor(decNumber / 2);
- }
-
- while (!remStack.isEmpty()){
- binaryString += remStack.pop().toString();
- }
-
- return binaryString;
-}
-
-console.log(divideBy2(233));
-console.log(divideBy2(10));
-console.log(divideBy2(1000));
-
-/*
- The folow algorithm converts from base 10 to any base
- */
-function baseConverter(decNumber, base){
-
- var remStack = new Stack(),
- rem,
- baseString = '',
- digits = '0123456789ABCDEF';
-
- while (decNumber > 0){
- rem = Math.floor(decNumber % base);
- remStack.push(rem);
- decNumber = Math.floor(decNumber / base);
- }
-
- while (!remStack.isEmpty()){
- baseString += digits[remStack.pop()];
- }
-
- return baseString;
-}
-
-console.log(baseConverter(100345, 2));
-console.log(baseConverter(100345, 8));
-console.log(baseConverter(100345, 16));
\ No newline at end of file
diff --git a/chapter03/05-TowerOfHanoi.html b/chapter03/05-TowerOfHanoi.html
deleted file mode 100755
index 8e11f147..00000000
--- a/chapter03/05-TowerOfHanoi.html
+++ /dev/null
@@ -1,11 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/chapter03/05-TowerOfHanoi.js b/chapter03/05-TowerOfHanoi.js
deleted file mode 100644
index ce0fd6dd..00000000
--- a/chapter03/05-TowerOfHanoi.js
+++ /dev/null
@@ -1,26 +0,0 @@
-function towerOfHanoi(n, from, to, helper){
-
- if (n > 0){
- towerOfHanoi(n-1, from, helper, to);
- to.push(from.pop());
- console.log('-----');
- console.log('Source: ' + from.toString());
- console.log('Dest: ' + to.toString());
- console.log('Helper: ' + helper.toString());
- towerOfHanoi(n-1, helper, to, from);
- }
-}
-
-var source = new Stack();
-source.push(3);
-source.push(2);
-source.push(1);
-
-var dest = new Stack();
-var helper = new Stack();
-
-towerOfHanoi(source.size(), source, dest, helper);
-
-source.print();
-helper.print();
-dest.print();
\ No newline at end of file
diff --git a/chapter04/01-Queue.js b/chapter04/01-Queue.js
deleted file mode 100644
index bb22df69..00000000
--- a/chapter04/01-Queue.js
+++ /dev/null
@@ -1,32 +0,0 @@
-function Queue() {
-
- let items = [];
-
- this.enqueue = function(element){
- items.push(element);
- };
-
- this.dequeue = function(){
- return items.shift();
- };
-
- this.front = function(){
- return items[0];
- };
-
- this.isEmpty = function(){
- return items.length == 0;
- };
-
- this.clear = function(){
- items = [];
- };
-
- this.size = function(){
- return items.length;
- };
-
- this.print = function(){
- console.log(items.toString());
- };
-}
diff --git a/chapter04/01-Queue2.js b/chapter04/01-Queue2.js
deleted file mode 100644
index d4bc9891..00000000
--- a/chapter04/01-Queue2.js
+++ /dev/null
@@ -1,49 +0,0 @@
-let Queue2 = (function () {
-
- const items = new WeakMap();
-
- 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;
- }
-
- front() {
- let q = items.get(this);
- return q[0];
- }
-
- isEmpty(){
- return items.get(this).length == 0;
- }
-
- size(){
- let q = items.get(this);
- return q.length;
- }
-
- clear(){
- items.set(this, []);
- }
-
- print(){
- console.log(this.toString());
- }
-
- toString(){
- return items.get(this).toString();
- }
- }
- return Queue2;
-})();
diff --git a/chapter04/02-UsingQueues.html b/chapter04/02-UsingQueues.html
deleted file mode 100644
index 611d3571..00000000
--- a/chapter04/02-UsingQueues.html
+++ /dev/null
@@ -1,12 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/chapter04/02-UsingQueues.js b/chapter04/02-UsingQueues.js
deleted file mode 100644
index 5411bad6..00000000
--- a/chapter04/02-UsingQueues.js
+++ /dev/null
@@ -1,12 +0,0 @@
-let queue = new Queue2();
-console.log(queue.isEmpty()); //outputs true
-queue.enqueue("John");
-queue.enqueue("Jack");
-queue.print();
-queue.enqueue("Camila");
-queue.print();
-console.log(queue.size()); //outputs 3
-console.log(queue.isEmpty()); //outputs false
-queue.dequeue();
-queue.dequeue();
-queue.print();
\ No newline at end of file
diff --git a/chapter04/03-PriorityQueue.html b/chapter04/03-PriorityQueue.html
deleted file mode 100755
index 924bf7c4..00000000
--- a/chapter04/03-PriorityQueue.html
+++ /dev/null
@@ -1,10 +0,0 @@
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/chapter04/03-PriorityQueue.js b/chapter04/03-PriorityQueue.js
deleted file mode 100644
index 3b029e4d..00000000
--- a/chapter04/03-PriorityQueue.js
+++ /dev/null
@@ -1,54 +0,0 @@
-function PriorityQueue() {
-
- let items = [];
-
- function QueueElement (element, priority){ // {1}
- this.element = element;
- this.priority = priority;
- }
-
- this.enqueue = function(element, priority){
- let queueElement = new QueueElement(element, priority);
-
- let added = false;
- for (let i=0; i
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/chapter04/03-PriorityQueue2.js b/chapter04/03-PriorityQueue2.js
deleted file mode 100644
index d629334b..00000000
--- a/chapter04/03-PriorityQueue2.js
+++ /dev/null
@@ -1,80 +0,0 @@
-let PriorityQueue2 = (function () {
-
- class QueueElement {
- constructor(element, priority){
- this.element = element;
- this.priority = priority;
- }
- }
-
- const items = new WeakMap();
-
- class PriorityQueue2 { //extends Queue2 { //with this approach the private properties are not reachable through inheritance
-
- constructor () {
- items.set(this, []);
- }
-
- enqueue(element, priority){
- let queueElement = new QueueElement(element, priority);
-
- let q = items.get(this);
-
- let added = false;
- for (let i=0; i
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/chapter04/04-HotPotato.js b/chapter04/04-HotPotato.js
deleted file mode 100644
index d0ce0d98..00000000
--- a/chapter04/04-HotPotato.js
+++ /dev/null
@@ -1,23 +0,0 @@
-function hotPotato (nameList, num){
-
- let queue = new Queue();
-
- for (let i=0; i 1){
- for (let i=0; i= 0 && position <= length){
-
- let node = new Node(element),
- current = head,
- previous,
- index = 0;
-
- if (position === 0){ //add on first position
-
- node.next = current;
- head = node;
-
- } else {
- while (index++ < position){
- previous = current;
- current = current.next;
- }
- node.next = current;
- previous.next = node;
- }
-
- length++; //update size of list
-
- return true;
-
- } else {
- return false;
- }
- };
-
- this.removeAt = function(position){
-
- //check for out-of-bounds values
- if (position > -1 && position < length){
-
- let current = head,
- previous,
- index = 0;
-
- //removing first item
- if (position === 0){
- head = current.next;
- } else {
-
- while (index++ < position){
-
- previous = current;
- current = current.next;
- }
-
- //link previous with current's next - skip it to remove
- previous.next = current.next;
- }
-
- length--;
-
- return current.element;
-
- } else {
- return null;
- }
- };
-
- this.remove = function(element){
-
- let index = this.indexOf(element);
- return this.removeAt(index);
- };
-
- this.indexOf = function(element){
-
- let current = head,
- index = 0;
-
- while (current) {
- if (element === current.element) {
- return index;
- }
- index++;
- current = current.next;
- }
-
- return -1;
- };
-
- this.isEmpty = function() {
- return length === 0;
- };
-
- this.size = function() {
- return length;
- };
-
- this.getHead = function(){
- return head;
- };
-
- this.toString = function(){
-
- let current = head,
- string = '';
-
- while (current) {
- string += current.element + (current.next ? ', ' : '');
- current = current.next;
- }
- return string;
-
- };
-
- this.print = function(){
- console.log(this.toString());
- };
-}
diff --git a/chapter05/01-LinkedList2.js b/chapter05/01-LinkedList2.js
deleted file mode 100644
index 98452857..00000000
--- a/chapter05/01-LinkedList2.js
+++ /dev/null
@@ -1,170 +0,0 @@
-let LinkedList2 = (function () {
-
- class Node {
- constructor(element){
- this.element = element;
- this.next = null;
- }
- }
-
- const length = new WeakMap();
- const head = new WeakMap();
-
- class LinkedList2 {
-
- constructor () {
- length.set(this, 0);
- head.set(this, null);
- }
-
- append(element) {
-
- let node = new Node(element),
- current;
-
- if (this.getHead() === null) { //first node on list
- head.set(this, node);
- } else {
-
- current = this.getHead();
-
- //loop the list until find last item
- while (current.next) {
- current = current.next;
- }
-
- //get last item and assign next to added item to make the link
- current.next = node;
- }
-
- //update size of list
- let l = this.size();
- l++;
- length.set(this, l);
- }
-
- insert(position, element) {
-
- //check for out-of-bounds values
- if (position >= 0 && position <= this.size()) {
-
- let node = new Node(element),
- current = this.getHead(),
- previous,
- index = 0;
-
- if (position === 0) { //add on first position
-
- node.next = current;
- head.set(this, node);
-
- } else {
- while (index++ < position) {
- previous = current;
- current = current.next;
- }
- node.next = current;
- previous.next = node;
- }
-
- //update size of list
- let l = this.size();
- l++;
- length.set(this, l);
-
- return true;
-
- } else {
- return false;
- }
- }
-
- removeAt(position) {
-
- //check for out-of-bounds values
- if (position > -1 && position < this.size()) {
-
- let current = this.getHead(),
- previous,
- index = 0;
-
- //removing first item
- if (position === 0) {
- head.set(this, current.next);
- } else {
-
- while (index++ < position) {
-
- previous = current;
- current = current.next;
- }
-
- //link previous with current's next - skip it to remove
- previous.next = current.next;
- }
-
- let l = this.size();
- l--;
- length.set(this, l);
-
- return current.element;
-
- } else {
- return null;
- }
- }
-
- remove(element) {
-
- let index = this.indexOf(element);
- return this.removeAt(index);
- }
-
- indexOf(element) {
-
- let current = this.getHead(),
- index = 0;
-
- while (current) {
- if (element === current.element) {
- return index;
- }
- index++;
- current = current.next;
- }
-
- return -1;
- }
-
- isEmpty() {
- return this.size() === 0;
- }
-
- size() {
- return length.get(this);
- }
-
- getHead() {
- return head.get(this);
- }
-
- toString() {
-
- let current = this.getHead(),
- string = '';
-
- while (current) {
- string += current.element + (current.next ? ', ' : '');
- current = current.next;
- }
- return string;
-
- }
-
- print() {
- console.log(this.toString());
- }
- }
-
- return LinkedList2;
-})();
diff --git a/chapter05/02-UsingLinkedLists.html b/chapter05/02-UsingLinkedLists.html
deleted file mode 100644
index 97210e70..00000000
--- a/chapter05/02-UsingLinkedLists.html
+++ /dev/null
@@ -1,12 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/chapter05/02-UsingLinkedLists.js b/chapter05/02-UsingLinkedLists.js
deleted file mode 100644
index bef9d86e..00000000
--- a/chapter05/02-UsingLinkedLists.js
+++ /dev/null
@@ -1,32 +0,0 @@
-let list = new LinkedList2();
-list.append(15);
-list.print();
-console.log(list.indexOf(15));
-list.append(10);
-list.print();
-console.log(list.indexOf(10));
-list.append(13);
-list.print();
-console.log(list.indexOf(13));
-console.log(list.indexOf(10));
-list.append(11);
-list.append(12);
-list.print();
-console.log(list.removeAt(1));
-list.print()
-console.log(list.removeAt(3));
-list.print();
-list.append(14);
-list.print();
-list.insert(0,16);
-list.print();
-list.insert(1,17);
-list.print();
-list.insert(list.size(),18);
-list.print();
-list.remove(16);
-list.print();
-list.remove(11);
-list.print();
-list.remove(18);
-list.print();
\ No newline at end of file
diff --git a/chapter05/03-DoublyLinkedList.js b/chapter05/03-DoublyLinkedList.js
deleted file mode 100644
index 6d4de9c5..00000000
--- a/chapter05/03-DoublyLinkedList.js
+++ /dev/null
@@ -1,217 +0,0 @@
-function DoublyLinkedList() {
-
- let Node = function(element){
-
- this.element = element;
- this.next = null;
- this.prev = null; //NEW
- };
-
- let length = 0;
- let head = null;
- let tail = null; //NEW
-
- this.append = function(element){
-
- let node = new Node(element),
- current;
-
- if (head === null){ //first node on list
- head = node;
- tail = node; //NEW
- } else {
-
- //attach to the tail node //NEW
- tail.next = node;
- node.prev = tail;
- tail = node;
- }
-
- length++; //update size of list
- };
-
- this.insert = function(position, element){
-
- //check for out-of-bounds values
- if (position >= 0 && position <= length){
-
- let node = new Node(element),
- current = head,
- previous,
- index = 0;
-
- if (position === 0){ //add on first position
-
- if (!head){ //NEW
- head = node;
- tail = node;
- } else {
- node.next = current;
- current.prev = node; //NEW {1}
- head = node;
- }
-
- } else if (position === length) { //last item //NEW
-
- current = tail; // {2}
- current.next = node;
- node.prev = current;
- tail = node;
-
- } else {
- while (index++ < position){ //{3}
- previous = current;
- current = current.next;
- }
- node.next = current;
- previous.next = node;
-
- current.prev = node; //NEW
- node.prev = previous; //NEW
- }
-
- length++; //update size of list
-
- return true;
-
- } else {
- return false;
- }
- };
-
- this.removeAt = function(position){
-
- //check for out-of-bounds values
- if (position > -1 && position < length){
-
- let current = head,
- previous,
- index = 0;
-
- //removing first item
- if (position === 0){
-
- head = current.next; // {1}
-
- //if there is only one item, then we update tail as well //NEW
- if (length === 1){ // {2}
- tail = null;
- } else {
- head.prev = null; // {3}
- }
-
- } else if (position === length-1){ //last item //NEW
-
- current = tail; // {4}
- tail = current.prev;
- tail.next = null;
-
- } else {
-
- while (index++ < position){ // {5}
-
- previous = current;
- current = current.next;
- }
-
- //link previous with current's next - skip it to remove
- previous.next = current.next; // {6}
- current.next.prev = previous; //NEW
- }
-
- length--;
-
- return current.element;
-
- } else {
- return null;
- }
- };
-
- this.remove = function(element){
-
- let index = this.indexOf(element);
- return this.removeAt(index);
- };
-
- this.indexOf = function(element){
-
- let current = head,
- index = -1;
-
- //check first item
- if (element == current.element){
- return 0;
- }
-
- index++;
-
- //check in the middle of the list
- while(current.next){
-
- if (element == current.element){
- return index;
- }
-
- current = current.next;
- index++;
- }
-
- //check last item
- if (element == current.element){
- return index;
- }
-
- return -1;
- };
-
- this.isEmpty = function() {
- return length === 0;
- };
-
- this. size = function() {
- return length;
- };
-
- this.toString = function(){
-
- let current = head,
- s = current ? current.element : '';
-
- while(current && current.next){
- current = current.next;
- s += ', ' + current.element;
- }
-
- return s;
- };
-
- this.inverseToString = function() {
-
- let current = tail,
- s = current ? current.element : '';
-
- while(current && current.prev){
- current = current.prev;
- s += ', ' + current.element;
- }
-
- return s;
- };
-
- this.print = function(){
- console.log(this.toString());
- };
-
- this.printInverse = function(){
- console.log(this.inverseToString());
- };
-
- this.getHead = function(){
- return head;
- };
-
- this.getTail = function(){
- return tail;
- }
-}
\ No newline at end of file
diff --git a/chapter05/03-DoublyLinkedList2.js b/chapter05/03-DoublyLinkedList2.js
deleted file mode 100644
index 9fe7d87b..00000000
--- a/chapter05/03-DoublyLinkedList2.js
+++ /dev/null
@@ -1,242 +0,0 @@
-let DoublyLinkedList2 = (function () {
-
- class Node {
- constructor(element) {
- this.element = element;
- this.next = null;
- this.prev = null; //NEW
- }
- }
-
- const length = new WeakMap();
- const head = new WeakMap();
- const tail = new WeakMap(); //NEW
-
- class DoublyLinkedList2 {
-
- constructor () {
- length.set(this, 0);
- head.set(this, null);
- tail.set(this, null);
- }
-
- append(element) {
-
- let node = new Node(element),
- current, _tail;
-
- if (this.getHead() === null) { //first node on list
- head.set(this, node);
- tail.set(this, node); //NEW
- } else {
- //attach to the tail node //NEW
- _tail = this.getTail();
- _tail.next = node;
- node.prev = _tail;
- tail.set(this, node);
- }
-
- //update size of list
- let l = this.size();
- l++;
- length.set(this, l);
- }
-
- insert(position, element) {
-
- //check for out-of-bounds values
- if (position >= 0 && position <= this.size()) {
-
- let node = new Node(element),
- current = this.getHead(),
- previous,
- index = 0;
-
- if (position === 0) { //add on first position
-
- if (!this.getHead()) { //NEW
- head.set(this, node);
- tail.set(this, node);
- } else {
- node.next = current;
- current.prev = node; //NEW {1}
- head.set(this, node);
- }
-
- } else if (position === this.size()) { //last item //NEW
-
- current = tail; // {2}
- current.next = node;
- node.prev = current;
- tail.set(this, node);
-
- } else {
- while (index++ < position) { //{3}
- previous = current;
- current = current.next;
- }
- node.next = current;
- previous.next = node;
-
- current.prev = node; //NEW
- node.prev = previous; //NEW
- }
-
- //update size of list
- let l = this.size();
- l++;
- length.set(this, l);
-
- return true;
-
- } else {
- return false;
- }
- }
-
- removeAt(position) {
-
- //check for out-of-bounds values
- if (position > -1 && position < this.size()) {
-
- let _head = this.getHead(),
- _tail = this.getTail(),
- current = _head,
- previous,
- index = 0;
-
- //removing first item
- if (position === 0) {
-
- _head = current.next; // {1}
-
- //if there is only one item, then we update tail as well //NEW
- if (this.size() === 1) { // {2}
- _tail = null;
- } else {
- _head.prev = null; // {3}
- }
-
- } else if (position === this.size() - 1) { //last item //NEW
-
- current = _tail; // {4}
- _tail = current.prev;
- _tail.next = null;
-
- } else {
-
- while (index++ < position) { // {5}
-
- previous = current;
- current = current.next;
- }
-
- //link previous with current's next - skip it to remove
- previous.next = current.next; // {6}
- current.next.prev = previous; //NEW
- }
-
- head.set(this,_head);
- tail.set(this,_tail);
-
- //update size of list
- let l = this.size();
- l--;
- length.set(this, l);
-
- return current.element;
-
- } else {
- return null;
- }
- }
-
- remove(element) {
-
- let index = this.indexOf(element);
- return this.removeAt(index);
- }
-
- indexOf(element) {
-
- let current = this.getHead(),
- index = -1;
-
- //check first item
- if (element == current.element) {
- return 0;
- }
-
- index++;
-
- //check in the middle of the list
- while (current.next) {
-
- if (element == current.element) {
- return index;
- }
-
- current = current.next;
- index++;
- }
-
- //check last item
- if (element == current.element) {
- return index;
- }
-
- return -1;
- }
-
- isEmpty() {
- return this.size() === 0;
- }
-
- size() {
- return length.get(this);
- }
-
- toString() {
-
- let current = this.getHead(),
- s = current ? current.element : '';
-
- while (current && current.next) {
- current = current.next;
- s += ', ' + current.element;
- }
-
- return s;
- }
-
- inverseToString() {
-
- let current = this.getTail(),
- s = current ? current.element : '';
-
- while (current && current.prev) {
- current = current.prev;
- s += ', ' + current.element;
- }
-
- return s;
- }
-
- print() {
- console.log(this.toString());
- }
-
- printInverse() {
- console.log(this.inverseToString());
- }
-
- getHead() {
- return head.get(this);
- }
-
- getTail() {
- return tail.get(this);
- }
- }
- return DoublyLinkedList2;
-})();
\ No newline at end of file
diff --git a/chapter05/04-UsingDoublyLinkedLists.html b/chapter05/04-UsingDoublyLinkedLists.html
deleted file mode 100644
index 58f959d5..00000000
--- a/chapter05/04-UsingDoublyLinkedLists.html
+++ /dev/null
@@ -1,12 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/chapter05/04-UsingDoublyLinkedLists.js b/chapter05/04-UsingDoublyLinkedLists.js
deleted file mode 100644
index 9ad4a17c..00000000
--- a/chapter05/04-UsingDoublyLinkedLists.js
+++ /dev/null
@@ -1,49 +0,0 @@
-let list = new DoublyLinkedList2();
-
-list.append(15);
-list.print();
-list.printInverse();
-
-list.append(16);
-list.print();
-list.printInverse();
-
-list.append(17);
-list.print();
-list.printInverse();
-
-list.insert(0,13);
-list.print();
-list.printInverse();
-
-list.insert(4,18);
-list.print();
-list.printInverse();
-
-list.insert(1,14);
-list.print();
-list.printInverse();
-
-list.removeAt(0);
-list.print();
-list.printInverse();
-
-list.removeAt(list.size()-1);
-list.print();
-list.printInverse();
-
-list.removeAt(1);
-list.print();
-list.printInverse();
-
-list.remove(16);
-list.print();
-list.printInverse();
-
-list.remove(14);
-list.print();
-list.printInverse();
-
-list.remove(17);
-list.print();
-list.printInverse();
\ No newline at end of file
diff --git a/chapter05/05-CircularLinkedList.js b/chapter05/05-CircularLinkedList.js
deleted file mode 100644
index c3151148..00000000
--- a/chapter05/05-CircularLinkedList.js
+++ /dev/null
@@ -1,190 +0,0 @@
-function CircularLinkedList() {
-
- let Node = function(element){
-
- this.element = element;
- this.next = null;
- };
-
- let length = 0;
- let head = null;
-
- this.append = function(element){
-
- let node = new Node(element),
- current;
-
- if (head === null){ //first node on list
- head = node;
- } else {
-
- current = head;
-
- //loop the list until find last item
- while(current.next !== head){ //last element will be head instead of NULL
- current = current.next;
- }
-
- //get last item and assign next to added item to make the link
- current.next = node;
- }
-
- //set node.next to head - to have circular list
- node.next = head;
-
- length++; //update size of list
- };
-
- this.insert = function(position, element){
-
- //check for out-of-bounds values
- if (position >= 0 && position <= length){
-
- let node = new Node(element),
- current = head,
- previous,
- index = 0;
-
- if (position === 0){ //add on first position
-
- if(!head){ // if no node in list
- head = node;
- node.next = head;
- }else{
- node.next = current;
-
- //update last element
- while(current.next !== head){ //last element will be head instead of NULL
- current = current.next;
- }
-
- head = node;
- current.next = head;
- }
-
-
- } else {
- while (index++ < position){
- previous = current;
- current = current.next;
- }
- node.next = current;
- previous.next = node;
- }
-
- length++; //update size of list
-
- return true;
-
- } else {
- return false;
- }
- };
-
- this.removeAt = function(position){
-
- //check for out-of-bounds values
- if (position > -1 && position < length){
-
- let current = head,
- previous,
- index = 0;
-
- //removing first item
- if (position === 0){
-
- while(current.next !== head){ //needs to update last element first
- current = current.next;
- }
-
- head = head.next;
- current.next = head;
-
- } else { //no need to update last element for circular list
-
- while (index++ < position){
-
- previous = current;
- current = current.next;
- }
-
- //link previous with current's next - skip it to remove
- previous.next = current.next;
- }
-
- length--;
-
- return current.element;
-
- } else {
- return null;
- }
- };
-
- this.remove = function(element){
-
- let index = this.indexOf(element);
- return this.removeAt(index);
- };
-
- this.indexOf = function(element){
-
- let current = head,
- index = -1;
-
- //check first item
- if (element == current.element){
- return 0;
- }
-
- index++;
-
- //check in the middle of the list
- while(current.next !== head){
-
- if (element == current.element){
- return index;
- }
-
- current = current.next;
- index++;
- }
-
- //check last item
- if (element == current.element){
- return index;
- }
-
- return -1;
- };
-
- this.isEmpty = function() {
- return length === 0;
- };
-
- this.size = function() {
- return length;
- };
-
- this.getHead = function(){
- return head;
- };
-
- this.toString = function(){
-
- let current = head,
- s = current.element;
-
- while(current.next !== head){
- current = current.next;
- s += ', ' + current.element;
- }
-
- return s.toString();
- };
-
- this.print = function(){
- console.log(this.toString());
- };
-}
-
diff --git a/chapter05/05-CircularLinkedList2.js b/chapter05/05-CircularLinkedList2.js
deleted file mode 100644
index 6f7574ef..00000000
--- a/chapter05/05-CircularLinkedList2.js
+++ /dev/null
@@ -1,204 +0,0 @@
-let CircularLinkedList2 = (function () {
-
- class Node {
- constructor(element) {
- this.element = element;
- this.next = null;
- }
- }
-
- const length = new WeakMap();
- const head = new WeakMap();
-
- class CircularLinkedList2 {
-
- constructor () {
- length.set(this, 0);
- head.set(this, null);
- }
-
- append(element) {
-
- let node = new Node(element),
- current;
-
- if (this.getHead() === null) { //first node on list
- head.set(this, node);
- } else {
-
- current = this.getHead();
-
- //loop the list until find last item
- while (current.next !== this.getHead()) { //last element will be head instead of NULL
- current = current.next;
- }
-
- //get last item and assign next to added item to make the link
- current.next = node;
- }
-
- //set node.next to head - to have circular list
- node.next = this.getHead();
-
- //update size of list
- let l = this.size();
- l++;
- length.set(this, l);
- }
-
- insert(position, element) {
-
- //check for out-of-bounds values
- if (position >= 0 && position <= this.size()) {
-
- let node = new Node(element),
- current = this.getHead(),
- previous,
- index = 0;
-
- if (position === 0) { //add on first position
-
- if(!this.getHead()) { // if no node in list
- head.set(this, node);
- node.next = this.getHead();
- } else {
- node.next = current;
- //update last element
- while(current.next !== this.getHead()) { //last element will be head instead of NULL
- current = current.next;
- }
- head.set(this, node);
- current.next = this.getHead();
- }
-
- } else {
- while (index++ < position) {
- previous = current;
- current = current.next;
- }
- node.next = current;
- previous.next = node;
- }
-
- //update size of list
- let l = this.size();
- l++;
- length.set(this, l);
-
- return true;
-
- } else {
- return false;
- }
- }
-
- removeAt(position) {
-
- //check for out-of-bounds values
- if (position > -1 && position < this.size()) {
-
- let current = this.getHead(),
- previous,
- index = 0;
-
- //removing first item
- if (position === 0) {
-
- while (current.next !== this.getHead()) { //needs to update last element first
- current = current.next;
- }
-
- head.set(this, this.getHead().next);
- current.next = this.getHead();
-
- } else { //no need to update last element for circular list
-
- while (index++ < position) {
-
- previous = current;
- current = current.next;
- }
-
- //link previous with current's next - skip it to remove
- previous.next = current.next;
- }
-
- let l = this.size();
- l--;
- length.set(this, l);
-
- return current.element;
-
- } else {
- return null;
- }
- }
-
- remove(element) {
-
- let index = this.indexOf(element);
- return this.removeAt(index);
- }
-
- indexOf(element) {
-
- let current = this.getHead(),
- index = -1;
-
- //check first item
- if (element == current.element) {
- return 0;
- }
-
- index++;
-
- //check in the middle of the list
- while (current.next !== this.getHead()) {
-
- if (element == current.element) {
- return index;
- }
-
- current = current.next;
- index++;
- }
-
- //check last item
- if (element == current.element) {
- return index;
- }
-
- return -1;
- }
-
- isEmpty() {
- return this.size() === 0;
- }
-
- size() {
- return length.get(this);
- }
-
- getHead() {
- return head.get(this);
- }
-
- toString() {
-
- let current = this.getHead(),
- s = current.element;
-
- while (current.next !== this.getHead()) {
- current = current.next;
- s += ', ' + current.element;
- }
-
- return s.toString();
- }
-
- print() {
- console.log(this.toString());
- }
- }
- return CircularLinkedList2;
-})();
diff --git a/chapter05/06-UsingCircularLinkedList.html b/chapter05/06-UsingCircularLinkedList.html
deleted file mode 100644
index ab39ba27..00000000
--- a/chapter05/06-UsingCircularLinkedList.html
+++ /dev/null
@@ -1,12 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/chapter05/06-UsingCircularLinkedList.js b/chapter05/06-UsingCircularLinkedList.js
deleted file mode 100644
index a1feebbb..00000000
--- a/chapter05/06-UsingCircularLinkedList.js
+++ /dev/null
@@ -1,28 +0,0 @@
-let circularLinkedList = new CircularLinkedList2();
-
-circularLinkedList.append(15);
-circularLinkedList.print();
-
-circularLinkedList.append(16);
-circularLinkedList.print();
-
-circularLinkedList.insert(0,14);
-circularLinkedList.print();
-
-circularLinkedList.insert(1,14.5);
-circularLinkedList.print();
-
-circularLinkedList.insert(4,17);
-circularLinkedList.print();
-
-circularLinkedList.removeAt(0);
-circularLinkedList.print();
-
-circularLinkedList.removeAt(1);
-circularLinkedList.print();
-
-circularLinkedList.removeAt(2);
-circularLinkedList.print();
-
-console.log(circularLinkedList.indexOf(14.5));
-console.log(circularLinkedList.indexOf(16));
\ No newline at end of file
diff --git a/chapter06/01-Set.js b/chapter06/01-Set.js
deleted file mode 100644
index 3fa90281..00000000
--- a/chapter06/01-Set.js
+++ /dev/null
@@ -1,142 +0,0 @@
-/**
- * ECMSCRIPT 6 already have a Set class implementation:
- * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
- * We will try to copy the same functionalities
- * @constructor
- */
-function Set() {
-
- let items = {};
-
- this.add = function(value){
- if (!this.has(value)){
- items[value] = value;
- return true;
- }
- return false;
- };
-
- this.delete = function(value){
- if (this.has(value)){
- delete items[value];
- return true;
- }
- return false;
- };
-
- this.has = function(value){
- return items.hasOwnProperty(value);
- //return value in items;
- };
-
- this.clear = function(){
- items = {};
- };
-
- /**
- * Modern browsers function
- * IE9+, FF4+, Chrome5+, Opera12+, Safari5+
- * @returns {Number}
- */
- this.size = function(){
- return Object.keys(items).length;
- };
-
- /**
- * cross browser compatibility - legacy browsers
- * for modern browsers use size function
- * @returns {number}
- */
- this.sizeLegacy = function(){
- let count = 0;
- for(let key in items) {
- if(items.hasOwnProperty(key))
- ++count;
- }
- return count;
- };
-
- /**
- * Modern browsers function
- * IE9+, FF4+, Chrome5+, Opera12+, Safari5+
- * @returns {Array}
- */
- this.values = function(){
- let values = [];
- for (let i=0, keys=Object.keys(items); i otherSet.size()){ //{1}
- return false;
- } else {
- let values = this.values();
- for (let i=0; i otherSet.size()){
- return false;
- } else {
- let values = this.values();
- for (let i=0; i
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/chapter06/02-UsingSets.js b/chapter06/02-UsingSets.js
deleted file mode 100644
index e74269ac..00000000
--- a/chapter06/02-UsingSets.js
+++ /dev/null
@@ -1,18 +0,0 @@
-let set = new 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
-console.log(set.sizeLegacy()); //3
-
-set.delete(1);
-console.log(set.values()); //outputs [2]
-
-set.delete(2);
-console.log(set.values()); //outputs []
\ No newline at end of file
diff --git a/chapter06/03-Operations.html b/chapter06/03-Operations.html
deleted file mode 100755
index ff01c7ae..00000000
--- a/chapter06/03-Operations.html
+++ /dev/null
@@ -1,11 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/chapter06/03-Operations.js b/chapter06/03-Operations.js
deleted file mode 100644
index dc7ece35..00000000
--- a/chapter06/03-Operations.js
+++ /dev/null
@@ -1,65 +0,0 @@
-//--------- Union ----------
-
-let setA = new Set();
-setA.add(1);
-setA.add(2);
-setA.add(3);
-
-let setB = new Set();
-setB.add(3);
-setB.add(4);
-setB.add(5);
-setB.add(6);
-
-let unionAB = setA.union(setB);
-console.log(unionAB.values());
-
-
-//--------- Intersection ----------
-
-let setA = new Set();
-setA.add(1);
-setA.add(2);
-setA.add(3);
-
-let setB = new Set();
-setB.add(2);
-setB.add(3);
-setB.add(4);
-
-let intersectionAB = setA.intersection(setB);
-console.log(intersectionAB.values());
-
-//--------- Difference ----------
-
-let setA = new Set();
-setA.add(1);
-setA.add(2);
-setA.add(3);
-
-let setB = new Set();
-setB.add(2);
-setB.add(3);
-setB.add(4);
-
-let differenceAB = setA.difference(setB);
-console.log(differenceAB.values());
-
-//--------- Subset ----------
-
-let setA = new Set();
-setA.add(1);
-setA.add(2);
-
-let setB = new Set();
-setB.add(1);
-setB.add(2);
-setB.add(3);
-
-let setC = new Set();
-setC.add(2);
-setC.add(3);
-setC.add(4);
-
-console.log(setA.subset(setB));
-console.log(setA.subset(setC));
diff --git a/chapter06/04-UsingES6Set.js b/chapter06/04-UsingES6Set.js
deleted file mode 100644
index a39e4100..00000000
--- a/chapter06/04-UsingES6Set.js
+++ /dev/null
@@ -1,71 +0,0 @@
-let set = new Set();
-
-set.add(1);
-console.log(set.values()); //outputs @Iterator
-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.delete(1);
-console.log(set.values()); //outputs [2]
-
-set.delete(2);
-console.log(set.values()); //outputs []
-
-let setA = new Set();
-setA.add(1);
-setA.add(2);
-setA.add(3);
-
-let setB = new Set();
-setB.add(2);
-setB.add(3);
-setB.add(4);
-
-//--------- Union ----------
-let unionAb = new Set();
-for (let x of setA) unionAb.add(x);
-for (let x of setB) unionAb.add(x);
-console.log(unionAb);
-
-//--------- Intersection ----------
-let intersection = function(setA, setB){
- let intersectionSet = new Set();
-
- for (let x of setA){
- if (setB.has(x)){
- intersectionSet.add(x);
- }
- }
-
- return intersectionSet;
-};
-let intersectionAB = intersection(setA, setB);
-console.log(intersectionAB);
-
-//alternative - works on FF only
-//intersectionAb = new Set([x for (x of setA) if (setB.has(x))]);
-//console.log(intersectionAB);
-
-//--------- Difference ----------
-let difference = function(setA, setB){
- let differenceSet = new Set();
-
- for (let x of setA){
- if (!setB.has(x)){
- differenceSet.add(x);
- }
- }
-
- return differenceSet;
-};
-let differenceAB = difference(setA, setB);
-console.log(differenceAB);
-
-//alternative - works on FF only
-//differenceAB = new Set([x for (x of setA) if (!setB.has(x))]);
-//console.log(differenceAB);
diff --git a/chapter07/01-Dictionaries.js b/chapter07/01-Dictionaries.js
deleted file mode 100644
index a22ec419..00000000
--- a/chapter07/01-Dictionaries.js
+++ /dev/null
@@ -1,59 +0,0 @@
-function Dictionary(){
-
- var items = {};
-
- this.set = function(key, value){
- items[key] = value; //{1}
- };
-
- this.delete = function(key){
- if (this.has(key)){
- delete items[key];
- return true;
- }
- return false;
- };
-
- this.has = function(key){
- return items.hasOwnProperty(key);
- //return value in items;
- };
-
- this.get = function(key) {
- return this.has(key) ? items[key] : undefined;
- };
-
- this.clear = function(){
- items = {};
- };
-
- this.size = function(){
- return Object.keys(items).length;
- };
-
- this.keys = function(){
- return Object.keys(items);
- };
-
- this.values = function(){
- var values = [];
- for (var k in items) {
- if (this.has(k)) {
- values.push(items[k]);
- }
- }
- return values;
- };
-
- this.each = function(fn) {
- for (var k in items) {
- if (this.has(k)) {
- fn(k, items[k]);
- }
- }
- };
-
- this.getItems = function(){
- return items;
- }
-}
\ No newline at end of file
diff --git a/chapter07/02-UsingDictionaries.html b/chapter07/02-UsingDictionaries.html
deleted file mode 100755
index f0f8e0eb..00000000
--- a/chapter07/02-UsingDictionaries.html
+++ /dev/null
@@ -1,11 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/chapter07/02-UsingDictionaries.js b/chapter07/02-UsingDictionaries.js
deleted file mode 100644
index dc0bf258..00000000
--- a/chapter07/02-UsingDictionaries.js
+++ /dev/null
@@ -1,19 +0,0 @@
-var dictionary = new Dictionary();
-
-dictionary.set('Gandalf', 'gandalf@email.com');
-dictionary.set('John', 'johnsnow@email.com');
-dictionary.set('Tyrion', 'tyrion@email.com');
-
-console.log(dictionary.has('Gandalf')); //outputs true
-console.log(dictionary.size()); //outputs 3
-
-console.log(dictionary.keys()); //outputs ["Gandalf", "John", "Tyrion"]
-console.log(dictionary.values()); //outputs ["gandalf@email.com", "johnsnow@email.com", "tyrion@email.com"]
-console.log(dictionary.get('Tyrion')); //outputs tyrion@email.com
-
-dictionary.delete('John');
-
-console.log(dictionary.keys()); //outputs ["Gandalf", "Tyrion"]
-console.log(dictionary.values()); //outputs ["gandalf@email.com", "tyrion@email.com"]
-
-console.log(dictionary.getItems()); //Object {Gandalf: "gandalf@email.com", Tyrion: "tyrion@email.com"}
diff --git a/chapter07/03-HashTable.js b/chapter07/03-HashTable.js
deleted file mode 100755
index c72783aa..00000000
--- a/chapter07/03-HashTable.js
+++ /dev/null
@@ -1,46 +0,0 @@
-function HashTable() {
-
- var table = [];
-
- var loseloseHashCode = function (key) {
- var hash = 0;
- for (var i = 0; i < key.length; i++) {
- hash += key.charCodeAt(i);
- }
- return hash % 37;
- };
-
- var djb2HashCode = function (key) {
- var hash = 5381;
- for (var i = 0; i < key.length; i++) {
- hash = hash * 33 + key.charCodeAt(i);
- }
- return hash % 1013;
- };
-
- var hashCode = function (key) {
- return loseloseHashCode(key);
- };
-
- this.put = function (key, value) {
- var position = hashCode(key);
- console.log(position + ' - ' + key);
- table[position] = value;
- };
-
- this.get = function (key) {
- return table[hashCode(key)];
- };
-
- this.remove = function(key){
- table[hashCode(key)] = undefined;
- };
-
- this.print = function () {
- for (var i = 0; i < table.length; ++i) {
- if (table[i] !== undefined) {
- console.log(i + ": " + table[i]);
- }
- }
- };
-}
\ No newline at end of file
diff --git a/chapter07/04-UsingHash.html b/chapter07/04-UsingHash.html
deleted file mode 100755
index 104be603..00000000
--- a/chapter07/04-UsingHash.html
+++ /dev/null
@@ -1,11 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/chapter07/04-UsingHash.js b/chapter07/04-UsingHash.js
deleted file mode 100755
index d0735eeb..00000000
--- a/chapter07/04-UsingHash.js
+++ /dev/null
@@ -1,29 +0,0 @@
-var hash = new HashTable();
-
-hash.put('Gandalf', 'gandalf@email.com');
-hash.put('John', 'johnsnow@email.com');
-hash.put('Tyrion', 'tyrion@email.com');
-hash.put('Aaron', 'aaron@email.com');
-hash.put('Donnie', 'donnie@email.com');
-hash.put('Ana', 'ana@email.com');
-hash.put('Jonathan', 'jonathan@email.com');
-hash.put('Jamie', 'jamie@email.com');
-hash.put('Sue', 'sue@email.com');
-hash.put('Mindy', 'mindy@email.com');
-hash.put('Paul', 'paul@email.com');
-hash.put('Nathan', 'nathan@email.com');
-
-console.log('**** Printing Hash **** ');
-
-hash.print();
-
-console.log('**** Get **** ');
-
-console.log(hash.get('Gandalf'));
-console.log(hash.get('Loiane'));
-
-console.log('**** Remove **** ');
-
-hash.remove('Gandalf');
-console.log(hash.get('Gandalf'));
-hash.print();
\ No newline at end of file
diff --git a/chapter07/05-HashCollisionSeparateChaining.js b/chapter07/05-HashCollisionSeparateChaining.js
deleted file mode 100644
index 5cac0e7d..00000000
--- a/chapter07/05-HashCollisionSeparateChaining.js
+++ /dev/null
@@ -1,85 +0,0 @@
-function HashTableSeparateChaining(){
-
- var table = [];
-
- var ValuePair = function(key, value){
- this.key = key;
- this.value = value;
-
- this.toString = function() {
- return '[' + this.key + ' - ' + this.value + ']';
- }
- };
-
- var loseloseHashCode = function (key) {
- var hash = 0;
- for (var i = 0; i < key.length; i++) {
- hash += key.charCodeAt(i);
- }
- return hash % 37;
- };
-
- var hashCode = function(key){
- return loseloseHashCode(key);
- };
-
- this.put = function(key, value){
- var position = hashCode(key);
- console.log(position + ' - ' + key);
-
- if (table[position] == undefined) {
- table[position] = new LinkedList();
- }
- table[position].append(new ValuePair(key, value));
- };
-
- this.get = function(key) {
- var position = hashCode(key);
-
- if (table[position] !== undefined && !table[position].isEmpty()){
-
- //iterate linked list to find key/value
- var current = table[position].getHead();
-
- do {
- if (current.element.key === key){
- return current.element.value;
- }
- current = current.next;
- } while(current);
- }
- return undefined;
- };
-
- this.remove = function(key){
-
- var position = hashCode(key);
-
- if (table[position] !== undefined){
-
- //iterate linked list to find key/value
- var current = table[position].getHead();
-
- do {
- if (current.element.key === key){
- table[position].remove(current.element);
- if (table[position].isEmpty()){
- table[position] = undefined;
- }
- return true;
- }
- current = current.next;
- } while(current);
- }
-
- return false;
- };
-
- this.print = function() {
- for (var i = 0; i < table.length; ++i) {
- if (table[i] !== undefined) {
- console.log(table[i].toString());
- }
- }
- };
-}
\ No newline at end of file
diff --git a/chapter07/06-UsingHashCollisionSeparateChaining.html b/chapter07/06-UsingHashCollisionSeparateChaining.html
deleted file mode 100644
index d671e133..00000000
--- a/chapter07/06-UsingHashCollisionSeparateChaining.html
+++ /dev/null
@@ -1,12 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/chapter07/06-UsingHashCollisionSeparateChaining.js b/chapter07/06-UsingHashCollisionSeparateChaining.js
deleted file mode 100755
index 2a0d3c37..00000000
--- a/chapter07/06-UsingHashCollisionSeparateChaining.js
+++ /dev/null
@@ -1,40 +0,0 @@
-var hashTableSeparateChaining = new HashTableSeparateChaining();
-
-hashTableSeparateChaining.put('Gandalf', 'gandalf@email.com');
-hashTableSeparateChaining.put('John', 'johnsnow@email.com');
-hashTableSeparateChaining.put('Tyrion', 'tyrion@email.com');
-hashTableSeparateChaining.put('Aaron', 'aaron@email.com');
-hashTableSeparateChaining.put('Donnie', 'donnie@email.com');
-hashTableSeparateChaining.put('Ana', 'ana@email.com');
-hashTableSeparateChaining.put('Jonathan', 'jonathan@email.com');
-hashTableSeparateChaining.put('Jamie', 'jamie@email.com');
-hashTableSeparateChaining.put('Sue', 'sue@email.com');
-hashTableSeparateChaining.put('Mindy', 'mindy@email.com');
-hashTableSeparateChaining.put('Paul', 'paul@email.com');
-hashTableSeparateChaining.put('Nathan', 'nathan@email.com');
-
-console.log('**** Printing Hash **** ');
-
-hashTableSeparateChaining.print();
-
-console.log('**** Get **** ');
-
-console.log(hashTableSeparateChaining.get('Jamie'));
-console.log(hashTableSeparateChaining.get('Sue'));
-console.log(hashTableSeparateChaining.get('Jonathan'));
-console.log(hashTableSeparateChaining.get('Loiane'));
-
-console.log('**** Remove **** ');
-
-console.log(hashTableSeparateChaining.remove('Gandalf'));
-console.log(hashTableSeparateChaining.get('Gandalf'));
-hashTableSeparateChaining.print();
-
-console.log(hashTableSeparateChaining.remove('Sue'));
-hashTableSeparateChaining.print();
-
-console.log(hashTableSeparateChaining.remove('Jamie'));
-hashTableSeparateChaining.print();
-
-console.log(hashTableSeparateChaining.remove('Donnie'));
-hashTableSeparateChaining.print();
\ No newline at end of file
diff --git a/chapter07/07-HashCollisionLinearProbing.js b/chapter07/07-HashCollisionLinearProbing.js
deleted file mode 100644
index 4b1172be..00000000
--- a/chapter07/07-HashCollisionLinearProbing.js
+++ /dev/null
@@ -1,94 +0,0 @@
-function HashLinearProbing(){
-
- var table = [];
-
- var ValuePair = function(key, value){
- this.key = key;
- this.value = value;
-
- this.toString = function() {
- return '[' + this.key + ' - ' + this.value + ']';
- }
- };
-
- var loseloseHashCode = function (key) {
- var hash = 0;
- for (var i = 0; i < key.length; i++) {
- hash += key.charCodeAt(i);
- }
- return hash % 37;
- };
-
- var hashCode = function(key){
- return loseloseHashCode(key);
- };
-
- this.put = function(key, value){
- var position = hashCode(key);
- console.log(position + ' - ' + key);
-
- if (table[position] == undefined) {
- table[position] = new ValuePair(key, value);
- } else {
- var index = ++position;
- while (table[index] != undefined){
- index++;
- }
- table[index] = new ValuePair(key, value);
- }
- };
-
- this.get = function(key) {
- var position = hashCode(key);
-
- if (table[position] !== undefined){
- if (table[position].key === key) {
- return table[position].value;
- } else {
- var index = ++position;
- while (table[index] !== undefined && (table[index] && table[index].key !== key)){
- index++;
- }
- if (table[index] && table[index].key === key) {
- return table[index].value;
- }
- }
- } else { //search for possible deleted value
- var index = ++position;
- while (table[index] == undefined || index == table.length ||
- (table[index] !== undefined && table[index] && table[index].key !== key)){
- index++;
- }
- if (table[index] && table[index].key === key) {
- return table[index].value;
- }
- }
- return undefined;
- };
-
- this.remove = function(key){
- var position = hashCode(key);
-
- if (table[position] !== undefined){
- if (table[position].key === key) {
- table[position] = undefined;
- } else {
- var index = ++position;
- while (table[index] === undefined || table[index].key !== key){
- index++;
- }
- if (table[index].key === key) {
- table[index] = undefined;
- }
- }
- }
- };
-
- this.print = function() {
- for (var i = 0; i < table.length; ++i) {
- if (table[i] !== undefined) {
- console.log(i + ' -> ' + table[i].toString());
- }
- }
- };
-}
diff --git a/chapter07/08-UsingHashCollisionLinearProbing.html b/chapter07/08-UsingHashCollisionLinearProbing.html
deleted file mode 100755
index f5fd9ad5..00000000
--- a/chapter07/08-UsingHashCollisionLinearProbing.html
+++ /dev/null
@@ -1,11 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/chapter07/08-UsingHashCollisionLinearProbing.js b/chapter07/08-UsingHashCollisionLinearProbing.js
deleted file mode 100644
index 36a33e61..00000000
--- a/chapter07/08-UsingHashCollisionLinearProbing.js
+++ /dev/null
@@ -1,37 +0,0 @@
-var hashLinearProbing = new HashLinearProbing();
-
-hashLinearProbing.put('Gandalf', 'gandalf@email.com');
-hashLinearProbing.put('John', 'johnsnow@email.com');
-hashLinearProbing.put('Tyrion', 'tyrion@email.com');
-hashLinearProbing.put('Aaron', 'aaron@email.com');
-hashLinearProbing.put('Donnie', 'donnie@email.com');
-hashLinearProbing.put('Ana', 'ana@email.com');
-hashLinearProbing.put('Jonathan', 'jonathan@email.com');
-hashLinearProbing.put('Jamie', 'jamie@email.com');
-hashLinearProbing.put('Sue', 'sue@email.com');
-hashLinearProbing.put('Mindy', 'mindy@email.com');
-hashLinearProbing.put('Paul', 'paul@email.com');
-hashLinearProbing.put('Nathan', 'nathan@email.com');
-
-console.log('**** Printing Hash **** ');
-
-hashLinearProbing.print();
-
-console.log('**** Get **** ');
-
-console.log(hashLinearProbing.get('Nathan'));
-console.log(hashLinearProbing.get('Loiane'));
-
-console.log('**** Remove **** ');
-
-hashLinearProbing.remove('Gandalf');
-console.log(hashLinearProbing.get('Gandalf'));
-hashLinearProbing.print();
-
-console.log('**** Remove Test 2 **** ');
-console.log('Removing Jonathan', hashLinearProbing.remove('Jonathan'));
-console.log('**** Print **** ');
-hashLinearProbing.print();
-console.log('Get Jamie', hashLinearProbing.get('Jamie'));
-console.log('**** Print **** ');
-hashLinearProbing.print();
\ No newline at end of file
diff --git a/chapter07/09-ES6Map.js b/chapter07/09-ES6Map.js
deleted file mode 100644
index 5e0c9dae..00000000
--- a/chapter07/09-ES6Map.js
+++ /dev/null
@@ -1,17 +0,0 @@
-var map = new Map();
-
-map.set('Gandalf', 'gandalf@email.com');
-map.set('John', 'johnsnow@email.com');
-map.set('Tyrion', 'tyrion@email.com');
-
-console.log(map.has('Gandalf')); //outputs true
-console.log(map.size); //outputs 3
-
-console.log(map.keys()); //outputs ["Gandalf", "John", "Tyrion"]
-console.log(map.values()); //outputs ["gandalf@email.com", "johnsnow@email.com", "tyrion@email.com"]
-console.log(map.get('Tyrion')); //outputs tyrion@email.com
-
-map.delete('John');
-
-console.log(map.keys()); //outputs ["Gandalf", "Tyrion"]
-console.log(map.values()); //outputs ["gandalf@email.com", "tyrion@email.com"]
\ No newline at end of file
diff --git a/chapter07/10-ES6WeakMap.js b/chapter07/10-ES6WeakMap.js
deleted file mode 100644
index 8efa16b8..00000000
--- a/chapter07/10-ES6WeakMap.js
+++ /dev/null
@@ -1,18 +0,0 @@
-var map = new WeakMap();
-
-var ob1 = {name:'Gandalf'},
- ob2 = {name:'John'},
- ob3 = {name:'Tyrion'};
-
-map.set(ob1, 'gandalf@email.com');
-map.set(ob2, 'johnsnow@email.com');
-map.set(ob3, 'tyrion@email.com');
-
-console.log(map.has(ob1)); //outputs true
-console.log(map.has(ob2)); //outputs true
-console.log(map.has(ob3)); //outputs true
-
-console.log(map.get(ob3)); //outputs tyrion@email.com
-
-map.delete(ob2);
-console.log(map.has(ob2)); //outputs false
diff --git a/chapter07/11-ES6WeakSet.js b/chapter07/11-ES6WeakSet.js
deleted file mode 100644
index e54a40de..00000000
--- a/chapter07/11-ES6WeakSet.js
+++ /dev/null
@@ -1,16 +0,0 @@
-var set = new WeakSet();
-
-var ob1 = {name:'Gandalf'},
- ob2 = {name:'John'},
- ob3 = {name:'Tyrion'};
-
-set.add(ob1);
-set.add(ob2);
-set.add(ob3);
-
-console.log(set.has(ob1)); //outputs true
-console.log(set.has(ob2)); //outputs true
-console.log(set.has(ob3)); //outputs true
-
-set.delete(ob2);
-console.log(set.has(ob2)); //outputs false
diff --git a/chapter08/01-BinarySearchTree.js b/chapter08/01-BinarySearchTree.js
deleted file mode 100755
index ae813fce..00000000
--- a/chapter08/01-BinarySearchTree.js
+++ /dev/null
@@ -1,187 +0,0 @@
-function BinarySearchTree() {
-
- var Node = function(key){
- this.key = key;
- this.left = null;
- this.right = null;
- };
-
- var root = null;
-
- this.insert = function(key){
-
- var newNode = new Node(key);
-
- //special case - first element
- if (root === null){
- root = newNode;
- } else {
- insertNode(root,newNode);
- }
- };
-
- var insertNode = function(node, newNode){
- if (newNode.key < node.key){
- if (node.left === null){
- node.left = newNode;
- } else {
- insertNode(node.left, newNode);
- }
- } else {
- if (node.right === null){
- node.right = newNode;
- } else {
- insertNode(node.right, newNode);
- }
- }
- };
-
- this.getRoot = function(){
- return root;
- };
-
- this.search = function(key){
-
- return searchNode(root, key);
- };
-
- var searchNode = function(node, key){
-
- if (node === null){
- return false;
- }
-
- if (key < node.key){
- return searchNode(node.left, key);
-
- } else if (key > node.key){
- return searchNode(node.right, key);
-
- } else { //element is equal to node.item
- return true;
- }
- };
-
- this.inOrderTraverse = function(callback){
- inOrderTraverseNode(root, callback);
- };
-
- var inOrderTraverseNode = function (node, callback) {
- if (node !== null) {
- inOrderTraverseNode(node.left, callback);
- callback(node.key);
- inOrderTraverseNode(node.right, callback);
- }
- };
-
- this.preOrderTraverse = function(callback){
- preOrderTraverseNode(root, callback);
- };
-
- var preOrderTraverseNode = function (node, callback) {
- if (node !== null) {
- callback(node.key);
- preOrderTraverseNode(node.left, callback);
- preOrderTraverseNode(node.right, callback);
- }
- };
-
- this.postOrderTraverse = function(callback){
- postOrderTraverseNode(root, callback);
- };
-
- var postOrderTraverseNode = function (node, callback) {
- if (node !== null) {
- postOrderTraverseNode(node.left, callback);
- postOrderTraverseNode(node.right, callback);
- callback(node.key);
- }
- };
-
- this.min = function() {
- return minNode(root);
- };
-
- var minNode = function (node) {
- if (node){
- while (node && node.left !== null) {
- node = node.left;
- }
-
- return node.key;
- }
- return null;
- };
-
- this.max = function() {
- return maxNode(root);
- };
-
- var maxNode = function (node) {
- if (node){
- while (node && node.right !== null) {
- node = node.right;
- }
-
- return node.key;
- }
- return null;
- };
-
- this.remove = function(element){
- root = removeNode(root, element);
- };
-
- var findMinNode = function(node){
- while (node && node.left !== null) {
- node = node.left;
- }
-
- return node;
- };
-
- var removeNode = function(node, element){
-
- if (node === null){
- return null;
- }
-
- if (element < node.key){
- node.left = removeNode(node.left, element);
- return node;
-
- } else if (element > node.key){
- node.right = removeNode(node.right, element);
- return node;
-
- } else { //element is equal to node.item
-
- //handle 3 special conditions
- //1 - a leaf node
- //2 - a node with only 1 child
- //3 - a node with 2 children
-
- //case 1
- if (node.left === null && node.right === null){
- node = null;
- return node;
- }
-
- //case 2
- if (node.left === null){
- node = node.right;
- return node;
-
- } else if (node.right === null){
- node = node.left;
- return node;
- }
-
- //case 3
- var aux = findMinNode(node.right);
- node.key = aux.key;
- node.right = removeNode(node.right, aux.key);
- return node;
- }
- };
-}
\ No newline at end of file
diff --git a/chapter08/02-UsingBinarySearchTree.html b/chapter08/02-UsingBinarySearchTree.html
deleted file mode 100644
index dd40cf48..00000000
--- a/chapter08/02-UsingBinarySearchTree.html
+++ /dev/null
@@ -1,11 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/chapter08/02-UsingBinarySearchTree.js b/chapter08/02-UsingBinarySearchTree.js
deleted file mode 100644
index eb139837..00000000
--- a/chapter08/02-UsingBinarySearchTree.js
+++ /dev/null
@@ -1,52 +0,0 @@
-var tree = new BinarySearchTree();
-
-tree.insert(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);
-
-console.log('********* in-order transverse ***********');
-function printNode(value){
- console.log(value);
-}
-tree.inOrderTraverse(printNode);
-
-console.log('********* pre-order transverse ***********');
-tree.preOrderTraverse(printNode);
-
-console.log('********* post-order transverse ***********');
-tree.postOrderTraverse(printNode);
-
-
-console.log('********* max and min ***********');
-console.log(tree.max());
-console.log(tree.min());
-console.log(tree.search(1) ? 'Key 1 found.' : 'Key 1 not found.');
-console.log(tree.search(8) ? 'Key 8 found.' : 'Key 8 not found.');
-
-
-console.log('********* remove 6 ***********');
-tree.remove(6);
-tree.inOrderTraverse(printNode);
-
-console.log('********* remove 5 ***********');
-tree.remove(5);
-tree.inOrderTraverse(printNode);
-
-console.log('********* remove 15 ***********');
-tree.remove(15);
-tree.inOrderTraverse(printNode);
-
-console.log('********* raw data structure ***********');
-console.log(tree.getRoot());
diff --git a/chapter08/03-AVLTree.js b/chapter08/03-AVLTree.js
deleted file mode 100644
index 2eed4f3e..00000000
--- a/chapter08/03-AVLTree.js
+++ /dev/null
@@ -1,149 +0,0 @@
-function AVLTree() {
-
- var Node = function(key){
- this.key = key;
- this.left = null;
- this.right = null;
- };
-
- var root = null;
-
- this.getRoot = function(){
- return root;
- };
-
- var heightNode = function(node) {
- if (node === null) {
- return -1;
- } else {
- return Math.max(heightNode(node.left), heightNode(node.right)) + 1;
- }
- };
-
- var rotationLL = function(node) {
- var tmp = node.left;
- node.left = tmp.right;
- tmp.right = node;
-
- return tmp;
- };
-
- var rotationRR = function(node) {
- var tmp = node.right;
- node.right = tmp.left;
- tmp.left = node;
-
- return tmp;
- };
-
- var rotationLR = function(node) {
- node.left = rotationRR(node.left);
- return rotationLL(node);
- };
-
- var rotationRL = function(node) {
- node.right = rotationLL(node.right);
- return rotationRR(node);
- };
-
- var insertNode = function(node, element) {
-
- if (node === null) {
- node = new Node(element);
-
- } else if (element < node.key) {
-
- node.left = insertNode(node.left, element);
-
- if (node.left !== null) {
-
- if ((heightNode(node.left) - heightNode(node.right)) > 1){
- if (element < node.left.key){
- node = rotationLL(node);
- } else {
- node = rotationLR(node);
- }
- }
- }
- } else if (element > node.key) {
-
- node.right = insertNode(node.right, element);
-
- if (node.right !== null) {
-
- if ((heightNode(node.right) - heightNode(node.left)) > 1){
-
- if (element > node.right.key){
- node = rotationRR(node);
- } else {
- node = rotationRL(node);
- }
- }
- }
- }
-
- return node;
- };
-
- this.insert = function(element) {
- root = insertNode(root, element);
- };
-
- var parentNode;
- var nodeToBeDeleted;
-
- var removeNode = function(node, element) {
- if (node === null) {
- return null;
- }
- parentNode = node;
-
- if (element < node.key) {
- node.left = removeNode(node.left, element);
- } else {
- nodeToBeDeleted = node;
- node.right = removeNode(node.right, element);
- }
-
- if (node === parentNode) { //remove node
- if (nodeToBeDeleted !== null && element === nodeToBeDeleted.key) {
- if (nodeToBeDeleted === parentNode) {
- node = node.left;
- } else {
- var tmp = nodeToBeDeleted.key;
- nodeToBeDeleted.key = parentNode.key;
- parentNode.key = tmp;
- node = node.right;
- }
- }
- } else { //do balancing
-
- if (node.left === undefined) node.left = null;
- if (node.right === undefined) node.right = null;
-
- if ((heightNode(node.left) - heightNode(node.right)) === 2) {
- if (element < node.left.key) {
- node = rotationLR(node);
- } else {
- node = rotationLL(node);
- }
- }
-
- if ((heightNode(node.right) - heightNode(node.left)) === 2) {
- if (element > node.right.key) {
- node = rotationRL(node);
- } else {
- node = rotationRR(node);
- }
- }
- }
-
- return node;
- };
-
- this.remove = function(element) {
- parentNode = null;
- nodeToBeDeleted = null;
- root = removeNode(root, element);
- };
-}
\ No newline at end of file
diff --git a/chapter08/04-UsingAVLTree.html b/chapter08/04-UsingAVLTree.html
deleted file mode 100644
index fda15f71..00000000
--- a/chapter08/04-UsingAVLTree.html
+++ /dev/null
@@ -1,11 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/chapter08/04-UsingAVLTree.js b/chapter08/04-UsingAVLTree.js
deleted file mode 100644
index fd77d395..00000000
--- a/chapter08/04-UsingAVLTree.js
+++ /dev/null
@@ -1,62 +0,0 @@
-var avlTree = new AVLTree();
-
-avlTree.insert(1);
-avlTree.insert(2);
-avlTree.insert(3);
-avlTree.insert(4);
-avlTree.insert(5);
-avlTree.insert(6);
-avlTree.insert(7);
-avlTree.insert(14);
-avlTree.insert(15);
-avlTree.insert(13);
-avlTree.insert(12);
-avlTree.insert(11);
-
-//RR rotation
-/*avlTree.insert(50);
-avlTree.insert(30);
-avlTree.insert(70);
-avlTree.insert(60);
-avlTree.insert(80);
-avlTree.insert(90);*/
-
-//LL rotation
-/*avlTree.insert(50);
-avlTree.insert(30);
-avlTree.insert(70);
-avlTree.insert(10);
-avlTree.insert(40);
-avlTree.insert(5);*/
-
-//LR rotation
-/*avlTree.insert(50);
-avlTree.insert(30);
-avlTree.insert(70);
-avlTree.insert(40);
-avlTree.insert(10);
-avlTree.insert(35);*/
-
-//RL rotation
-/*avlTree.insert(70);
-avlTree.insert(50);
-avlTree.insert(80);
-avlTree.insert(72);
-avlTree.insert(90);
-avlTree.insert(75);*/
-
-console.log('********* raw data structure ***********');
-console.log(avlTree.getRoot());
-
-/*avlTree.remove(12);
-avlTree.remove(15);
-avlTree.remove(11);
-avlTree.remove(14);
-avlTree.remove(13);
-avlTree.remove(7);
-avlTree.remove(6);
-avlTree.remove(2);
-avlTree.remove(4);
-
-console.log(avlTree.getRoot());*/
-
diff --git a/chapter08/05-RedBlackTree.js b/chapter08/05-RedBlackTree.js
deleted file mode 100644
index 7a985d2e..00000000
--- a/chapter08/05-RedBlackTree.js
+++ /dev/null
@@ -1,101 +0,0 @@
-function RedBlackTree() {
-
- var Colors = {
- RED: 0,
- BLACK: 1
- };
-
- var Node = function (key, color) {
- this.key = key;
- this.left = null;
- this.right = null;
- this.color = color;
-
- this.flipColor = function(){
- if (this.color === Colors.RED) {
- this.color = Colors.BLACK;
- } else {
- this.color = Colors.RED;
- }
- };
- };
-
- var root = null;
-
- this.getRoot = function () {
- return root;
- };
-
- var isRed = function(node){
- if (!node){
- return false;
- }
- return node.color === Colors.RED;
- };
-
- var flipColors = function(node){
- node.left.flipColor();
- node.right.flipColor();
- };
-
- var rotateLeft = function(node){
- var temp = node.right;
- if (temp !== null) {
- node.right = temp.left;
- temp.left = node;
- temp.color = node.color;
- node.color = Colors.RED;
- }
- return temp;
- };
-
- var rotateRight = function (node) {
- var temp = node.left;
- if (temp !== null) {
- node.left = temp.right;
- temp.right = node;
- temp.color = node.color;
- node.color = Colors.RED;
- }
- return temp;
- };
-
- var insertNode = function(node, element) {
-
- if (node === null) {
- return new Node(element, Colors.RED);
- }
-
- var newRoot = node;
-
- if (element < node.key) {
-
- node.left = insertNode(node.left, element);
-
- } else if (element > node.key) {
-
- node.right = insertNode(node.right, element);
-
- } else {
- node.key = element;
- }
-
- if (isRed(node.right) && !isRed(node.left)) {
- newRoot = rotateLeft(node);
- }
-
- if (isRed(node.left) && isRed(node.left.left)) {
- newRoot = rotateRight(node);
- }
- if (isRed(node.left) && isRed(node.right)) {
- flipColors(node);
- }
-
- return newRoot;
- };
-
- this.insert = function(element) {
- root = insertNode(root, element);
- root.color = Colors.BLACK;
- };
-}
diff --git a/chapter08/06-UsingRedBlackTree.html b/chapter08/06-UsingRedBlackTree.html
deleted file mode 100644
index f0fdfcc9..00000000
--- a/chapter08/06-UsingRedBlackTree.html
+++ /dev/null
@@ -1,11 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/chapter08/06-UsingRedBlackTree.js b/chapter08/06-UsingRedBlackTree.js
deleted file mode 100644
index 31136f99..00000000
--- a/chapter08/06-UsingRedBlackTree.js
+++ /dev/null
@@ -1,17 +0,0 @@
-var rbTree = new RedBlackTree();
-
-rbTree.insert(1);
-rbTree.insert(2);
-rbTree.insert(3);
-rbTree.insert(4);
-rbTree.insert(5);
-rbTree.insert(6);
-rbTree.insert(7);
-rbTree.insert(14);
-rbTree.insert(15);
-rbTree.insert(13);
-rbTree.insert(12);
-rbTree.insert(11);
-
-console.log('********* raw data structure ***********');
-console.log(rbTree.getRoot());
\ No newline at end of file
diff --git a/chapter09/01-Graph.js b/chapter09/01-Graph.js
deleted file mode 100644
index b7a1b847..00000000
--- a/chapter09/01-Graph.js
+++ /dev/null
@@ -1,172 +0,0 @@
-function Graph() {
-
- var vertices = []; //list
-
- var adjList = new Dictionary();
-
- this.addVertex = function(v){
- vertices.push(v);
- adjList.set(v, []); //initialize adjacency list with array as well;
- };
-
- this.addEdge = function(v, w){
- adjList.get(v).push(w);
- //adjList.get(w).push(v); //commented to run the improved DFS with topological sorting
- };
-
- this.toString = function(){
- var s = '';
- for (var i=0; i ';
- var neighbors = adjList.get(vertices[i]);
- for (var j=0; j
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/chapter09/02-UsingGraphs.js b/chapter09/02-UsingGraphs.js
deleted file mode 100755
index 3f143525..00000000
--- a/chapter09/02-UsingGraphs.js
+++ /dev/null
@@ -1,97 +0,0 @@
-var graph = new Graph();
-
-var myVertices = ['A','B','C','D','E','F','G','H','I'];
-
-for (var i=0; i max){
- max = fTimes[myVertices[i]];
- maxName = myVertices[i];
- }
- }
- s += ' - ' + maxName;
- delete fTimes[maxName];
-}
-console.log(s);
diff --git a/chapter09/03-ShortestPath.js b/chapter09/03-ShortestPath.js
deleted file mode 100644
index cdef7fbb..00000000
--- a/chapter09/03-ShortestPath.js
+++ /dev/null
@@ -1,76 +0,0 @@
-function ShortestPath(graph) {
-
- this.graph = graph;
-
- var INF = Number.MAX_SAFE_INTEGER;
-
- var minDistance = function(dist, visited){
-
- var min = INF,
- minIndex = -1;
-
- for (var v = 0; v < dist.length; v++){
- if (visited[v] == false && dist[v] <= min){
- min = dist[v];
- minIndex = v;
- }
- }
-
- return minIndex;
- };
-
- this.dijkstra = function(src){
-
- var dist = [],
- visited = [],
- length = this.graph.length;
-
- for (var i = 0; i < length; i++) {
- dist[i] = INF;
- visited[i] = false;
- }
-
- dist[src] = 0;
-
- for (var i = 0; i < length-1; i++){
-
- var u = minDistance(dist, visited);
-
- visited[u] = true;
-
- for (var v = 0; v < length; v++){
- if (!visited[v] && this.graph[u][v]!=0 && dist[u] != INF && dist[u]+this.graph[u][v] < dist[v]){
- dist[v] = dist[u] + this.graph[u][v];
- }
- }
- }
-
- return dist;
- };
-
- this.floydWarshall = function(){
-
- var dist = [],
- length = this.graph.length,
- i, j, k;
-
- for (i = 0; i < length; i++){
- dist[i] = [];
- for (j = 0; j < length; j++){
- dist[i][j] = this.graph[i][j];
- }
- }
-
- for (k = 0; k < length; k++){
- for (i = 0; i < length; i++){
- for (j = 0; j < length; j++){
- if (dist[i][k] + dist[k][j] < dist[i][j]){
- dist[i][j] = dist[i][k] + dist[k][j];
- }
- }
- }
- }
-
- return dist;
- }
-}
\ No newline at end of file
diff --git a/chapter09/04-UsingShortestPathAlgorithms.html b/chapter09/04-UsingShortestPathAlgorithms.html
deleted file mode 100644
index 422b9fc4..00000000
--- a/chapter09/04-UsingShortestPathAlgorithms.html
+++ /dev/null
@@ -1,11 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/chapter09/04-UsingShortestPathAlgorithms.js b/chapter09/04-UsingShortestPathAlgorithms.js
deleted file mode 100644
index 5bc5ac79..00000000
--- a/chapter09/04-UsingShortestPathAlgorithms.js
+++ /dev/null
@@ -1,45 +0,0 @@
-//adjacent matrix
-var i;
-
-var graph = [[0, 2, 4, 0, 0, 0],
- [0, 0, 2, 4, 2, 0],
- [0, 0, 0, 0, 3, 0],
- [0, 0, 0, 0, 0, 2],
- [0, 0, 0, 3, 0, 2],
- [0, 0, 0, 0, 0, 0]];
-
-var shortestPath = new ShortestPath(graph);
-
-console.log("********* Dijkstra's Algorithm - Shortest Path ***********");
-
-var dist = shortestPath.dijkstra(0);
-
-for (i = 0; i < dist.length; i++){
- console.log(i + '\t\t' + dist[i]);
-}
-
-console.log("********* Floyd-Warshall Algorithm - All-Pairs Shortest Path ***********");
-
-var INF = Number.MAX_SAFE_INTEGER;
-graph = [[0, 2, 4, INF, INF, INF],
- [INF, 0, 2, 4, 2, INF],
- [INF, INF, 0, INF, 3, INF],
- [INF, INF, INF, 0, INF, 2],
- [INF, INF, INF, 3, 0, 2],
- [INF, INF, INF, INF, INF, 0]];
-
-shortestPath = new ShortestPath(graph);
-
-dist = shortestPath.floydWarshall();
-
-var s = '';
-for (i=0; i
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/chapter09/06-UsingMinimumSpanningTree.js b/chapter09/06-UsingMinimumSpanningTree.js
deleted file mode 100644
index 286f1dff..00000000
--- a/chapter09/06-UsingMinimumSpanningTree.js
+++ /dev/null
@@ -1,29 +0,0 @@
-var i;
-
-var graph = [[0, 2, 4, 0, 0, 0],
- [2, 0, 2, 4, 2, 0],
- [4, 2, 0, 0, 3, 0],
- [0, 4, 0, 0, 3, 2],
- [0, 2, 3, 3, 0, 2],
- [0, 0, 0, 2, 2, 0]];
-
-var mst = new MinimumSpanningTree(graph);
-
-
-console.log("********* Prim's Algorithm - Minimum Spanning Tree ***********");
-
-var parent = mst.prim();
-
-console.log('Edge Weight');
-for (i = 1; i < graph.length; i++){
- console.log(parent[i] + ' - ' + i + ' ' + graph[i][parent[i]]);
-}
-
-console.log("********* Kruskal Algorithm - Minimum Spanning Tree ***********");
-
-parent = mst.kruskal();
-
-console.log('Edge Weight');
-for (i = 1; i < graph.length; i++){
- console.log(parent[i] + ' - ' + i + ' ' + graph[i][parent[i]]);
-}
\ No newline at end of file
diff --git a/chapter10/01-SortingSearchingAlgorithms.js b/chapter10/01-SortingSearchingAlgorithms.js
deleted file mode 100755
index 916e7403..00000000
--- a/chapter10/01-SortingSearchingAlgorithms.js
+++ /dev/null
@@ -1,417 +0,0 @@
-function ArrayList(){
-
- var array = [];
-
- this.insert = function(item){
- array.push(item);
- };
-
- var swap = function(array, index1, index2){
- var aux = array[index1];
- array[index1] = array[index2];
- array[index2] = aux;
- //ES2015 swap - Firefox only, for other browser, uncomment code above and coment line below
- //[array[index1], array[index2]] = [array[index2], array[index1]];
- };
-
- this.toString= function(){
- return array.join();
- };
-
- this.array= function(){
- return array;
- };
-
- this.bubbleSort = function(){
- var length = array.length;
-
- for (var i=0; i array[j+1]){
- console.log('swap ' + array[j] + ' with ' + array[j+1]);
- swap(array, j, j+1);
- }
- }
- }
- };
-
- this.modifiedBubbleSort = function(){
- var length = array.length;
-
- for (var i=0; i array[j+1]){
- console.log('swap ' + array[j] + ' with ' + array[j+1]);
- swap(j, j+1);
- }
- }
- }
-
- };
-
- this.selectionSort = function(){
- var length = array.length,
- indexMin;
-
- for (var i=0; iarray[j]){
- console.log('new index min ' + array[j]);
- indexMin = j;
- }
- }
- if (i !== indexMin){
- console.log('swap ' + array[i] + ' with ' + array[indexMin]);
- swap(i, indexMin);
- }
- }
- };
-
- this.insertionSort = function(){
- var length = array.length,
- j, temp;
- for (var i=1; i0 && array[j-1] > temp){
- console.log('shift ' + array[j-1]);
- array[j] = array[j-1];
- j--;
- }
- console.log('insert ' + temp);
- array[j] = temp;
- }
- };
-
- var insertionSort_ = function(array){
- var length = array.length,
- j, temp;
- for (var i=1; i0 && array[j-1] > temp){
- array[j] = array[j-1];
- j--;
- }
- array[j] = temp;
- }
- };
-
- this.mergeSort = function(){
- array = mergeSortRec(array);
- };
-
- var mergeSortRec = function(array){
-
- var length = array.length;
-
- if(length === 1) {
- console.log(array);
- return array;
- }
-
- var mid = Math.floor(length / 2),
- left = array.slice(0, mid),
- right = array.slice(mid, length);
-
- return merge(mergeSortRec(left), mergeSortRec(right));
- };
-
- var merge = function(left, right){
- var result = [],
- il = 0,
- ir = 0;
-
- while(il < left.length && ir < right.length) {
-
- if(left[il] < right[ir]) {
- result.push(left[il++]);
- } else{
- result.push(right[ir++]);
- }
- }
-
- while (il < left.length){
- result.push(left[il++]);
- }
-
- while (ir < right.length){
- result.push(right[ir++]);
- }
-
- console.log(result);
-
- return result;
- };
-
- this.quickSort = function(){
- quick(array, 0, array.length - 1);
- };
-
- var partition = function(array, left, right) {
-
- var pivot = array[Math.floor((right + left) / 2)],
- i = left,
- j = right;
-
- console.log('pivot is ' + pivot + '; left is ' + left + '; right is ' + right);
-
- while (i <= j) {
- while (array[i] < pivot) {
- i++;
- console.log('i = ' + i);
- }
-
- while (array[j] > pivot) {
- j--;
- console.log('j = ' + j);
- }
-
- if (i <= j) {
- console.log('swap ' + array[i] + ' with ' + array[j]);
- swap(array, i, j);
- i++;
- j--;
- }
- }
-
- return i;
- };
-
- var quick = function(array, left, right){
-
- var index;
-
- if (array.length > 1) {
-
- index = partition(array, left, right);
-
- if (left < index - 1) {
- quick(array, left, index - 1);
- }
-
- if (index < right) {
- quick(array, index, right);
- }
- }
- return array;
- };
-
- this.heapSort = function(){
- var heapSize = array.length;
-
- buildHeap(array);
-
- while (heapSize > 1) {
- heapSize--;
- console.log('swap (' + + array[0] + ',' + array[heapSize] + ')');
- swap(array, 0, heapSize);
- console.log('heapify ' + array.join());
- heapify(array, heapSize, 0);
- }
- };
-
- var buildHeap = function(array){
- console.log('building heap');
- var heapSize = array.length;
- for (var i = Math.floor(array.length / 2); i >= 0; i--) {
- heapify(array, heapSize, i);
- }
- console.log('heap created: ' + array.join());
- };
-
- var heapify = function(array, heapSize, i){
- var left = i * 2 + 1,
- right = i * 2 + 2,
- largest = i;
-
- if (left < heapSize && array[left] > array[largest]) {
- largest = left;
- }
-
- if (right < heapSize && array[right] > array[largest]) {
- largest = right;
- }
-
- console.log('Heapify Index = '+ i + ' and Heap Size = ' + heapSize);
-
- if (largest !== i) {
- console.log('swap index ' + i + ' with ' + largest + ' (' + + array[i] + ',' + array[largest] + ')');
- swap(array, i, largest);
- console.log('heapify ' + array.join());
- heapify(array, heapSize, largest);
- }
- };
-
- this.countingSort = function(){
-
- var i,
- maxValue = this.findMaxValue(),
- sortedIndex = 0,
- counts = new Array(maxValue + 1);
-
- for (i = 0; i < array.length; i++) {
- if (!counts[array[i]]) {
- counts[array[i]] = 0;
- }
- counts[array[i]]++;
- }
-
- console.log('Frequencies: ' + counts.join());
-
- for (i = 0; i < counts.length; i++) {
- while (counts[i] > 0) {
- array[sortedIndex++] = i;
- counts[i]--;
- }
- }
- };
-
- this.bucketSort = function(bucketSize){
-
- var i,
- minValue = this.findMinValue(),
- maxValue = this.findMaxValue(),
- BUCKET_SIZE = 5;
-
- console.log('minValue ' + minValue);
- console.log('maxValue ' + maxValue);
-
- bucketSize = bucketSize || BUCKET_SIZE;
- var bucketCount = Math.floor((maxValue - minValue) / bucketSize) + 1;
- var buckets = new Array(bucketCount);
- console.log('bucketSize = ' + bucketCount);
- for (i = 0; i < buckets.length; i++) {
- buckets[i] = [];
- }
-
- for (i = 0; i < array.length; i++) {
- buckets[Math.floor((array[i] - minValue) / bucketSize)].push(array[i]);
- console.log('pushing item ' + array[i] + ' to bucket index ' + Math.floor((array[i] - minValue) / bucketSize));
- }
-
- array = [];
- for (i = 0; i < buckets.length; i++) {
- insertionSort_(buckets[i]);
-
- console.log('bucket sorted ' + i + ': ' + buckets[i].join());
-
- for (var j = 0; j < buckets[i].length; j++) {
- array.push(buckets[i][j]);
- }
- }
- };
-
- this.radixSort = function(radixBase){
-
- var i,
- minValue = this.findMinValue(),
- maxValue = this.findMaxValue(),
- radixBase = radixBase || 10;
-
- // Perform counting sort for each significant digit), starting at 1
- var significantDigit = 1;
- while (((maxValue - minValue) / significantDigit) >= 1) {
- console.log('radix sort for digit ' + significantDigit);
- array = countingSortForRadix(array, radixBase, significantDigit, minValue);
- console.log(array.join());
- significantDigit *= radixBase;
- }
- };
-
- var countingSortForRadix = function(array, radixBase, significantDigit, minValue){
- var i, countsIndex,
- counts = new Array(radixBase),
- aux = new Array(radixBase);
-
- for (i = 0; i < radixBase; i++) {
- counts[i] = 0;
- }
-
- for (i = 0; i < array.length; i++) {
- countsIndex = Math.floor(((array[i] - minValue) / significantDigit) % radixBase);
- counts[countsIndex]++;
- }
-
- for (i = 1; i < radixBase; i++) {
- counts[i] += counts[i - 1];
- }
-
- for (i = array.length - 1; i >= 0; i--) {
- countsIndex = Math.floor(((array[i] - minValue) / significantDigit) % radixBase);
- aux[--counts[countsIndex]] = array[i];
- }
-
- for (i = 0; i < array.length; i++) {
- array[i] = aux[i];
- }
-
- return array;
- };
-
- this.sequentialSearch = function(item){
-
- for (var i=0; i array[i]){
- min = array[i];
- }
- }
-
- return min;
- };
-
- this.binarySearch = function(item){
- this.quickSort();
-
- var low = 0,
- high = array.length - 1,
- mid, element;
-
- while (low <= high){
- mid = Math.floor((low + high) / 2);
- element = array[mid];
- console.log('mid element is ' + element);
- if (element < item) {
- low = mid + 1;
- console.log('low is ' + low);
- } else if (element > item) {
- high = mid - 1;
- console.log('high is ' + high);
- } else {
- console.log('found it');
- return mid;
- }
- }
- return -1;
- };
-
-}
\ No newline at end of file
diff --git a/chapter10/02-UsingSortingAlgorithms.html b/chapter10/02-UsingSortingAlgorithms.html
deleted file mode 100755
index 7a666fdb..00000000
--- a/chapter10/02-UsingSortingAlgorithms.html
+++ /dev/null
@@ -1,11 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/chapter10/02-UsingSortingAlgorithms.js b/chapter10/02-UsingSortingAlgorithms.js
deleted file mode 100755
index 92b63e8f..00000000
--- a/chapter10/02-UsingSortingAlgorithms.js
+++ /dev/null
@@ -1,126 +0,0 @@
-function createNonSortedArray(size){
- var array = new ArrayList();
-
- for (var i = size; i> 0; i--){
- array.insert(i);
- }
-
- return array;
-}
-
-function createRandomNonSortedArray(){
- var array = new ArrayList();
-
- array.insert(3);
- array.insert(5);
- array.insert(1);
- array.insert(6);
- array.insert(4);
- array.insert(7);
- array.insert(2);
-
- return array;
-}
-
-function printArray(array){
- console.log(array.toString());
-}
-
-function createNonSortedArrayAndPrint(size){
- var array = createNonSortedArray(size);
- printArray(array);
-
- return array;
-}
-
-console.log('********** Bubble Sort **********');
-
-var array = createNonSortedArrayAndPrint(5);
-
-array.bubbleSort();
-
-printArray(array);
-
-console.log('********** Modified Bubble Sort **********');
-
-array = createNonSortedArrayAndPrint(5);
-
-array.modifiedBubbleSort();
-
-printArray(array);
-
-console.log('********** Selection Sort **********');
-
-array = createNonSortedArrayAndPrint(5);
-
-array.selectionSort();
-
-printArray(array);
-
-console.log('********** Insertion Sort **********');
-
-array = createNonSortedArrayAndPrint(5);
-
-array.insertionSort();
-
-printArray(array);
-
-console.log('********** Merge Sort **********');
-
-array = createNonSortedArrayAndPrint(8);
-
-array.mergeSort();
-
-printArray(array);
-
-console.log('********** Quick Sort **********');
-array = createRandomNonSortedArray();
-
-printArray(array);
-
-array.quickSort();
-
-printArray(array);
-
-console.log('********** Heap Sort **********');
-array = createRandomNonSortedArray();
-
-printArray(array);
-
-array.heapSort();
-
-printArray(array);
-
-
-console.log('********** Counting Sort **********');
-
-array = createNonSortedArrayAndPrint(8);
-
-array.countingSort();
-
-printArray(array);
-
-console.log('********** Bucket Sort **********');
-
-array = createNonSortedArrayAndPrint(8);
-
-array.bucketSort(3);
-
-printArray(array);
-
-console.log('********** Radix Sort **********');
-
-var array = new ArrayList();
-
-array.insert(30);
-array.insert(52);
-array.insert(13);
-array.insert(25);
-array.insert(31);
-array.insert(23);
-array.insert(2);
-
-array.radixSort();
-
-console.log('Result: ');
-printArray(array);
diff --git a/chapter10/03-UsingSearchingAlgorithms.html b/chapter10/03-UsingSearchingAlgorithms.html
deleted file mode 100755
index a4e4b6a3..00000000
--- a/chapter10/03-UsingSearchingAlgorithms.html
+++ /dev/null
@@ -1,11 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/chapter10/03-UsingSearchingAlgorithms.js b/chapter10/03-UsingSearchingAlgorithms.js
deleted file mode 100755
index 62201e80..00000000
--- a/chapter10/03-UsingSearchingAlgorithms.js
+++ /dev/null
@@ -1,33 +0,0 @@
-function createNonSortedArray(items){
- var array = new ArrayList();
-
- for (var i = items; i> 0; i--){
- array.insert(i);
- }
-
- return array;
-}
-
-var array = createNonSortedArray(5);
-
-console.log('********** Sequential Sort #3 **********');
-
-console.log(array.sequentialSearch(3));
-
-console.log('********** Min **********');
-
-console.log(array.findMinValue());
-
-console.log('********** Max **********');
-
-console.log(array.findMaxValue());
-
-console.log('********** Binary Search #3 **********');
-
-console.log(array.binarySearch(3));
-
-console.log('********** Binary Search #2 **********');
-
-var array = createNonSortedArray(8);
-
-console.log(array.binarySearch(2));
\ No newline at end of file
diff --git a/chapter11/01-Recursion.html b/chapter11/01-Recursion.html
deleted file mode 100755
index 5961583b..00000000
--- a/chapter11/01-Recursion.html
+++ /dev/null
@@ -1,10 +0,0 @@
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/chapter11/01-Recursion.js b/chapter11/01-Recursion.js
deleted file mode 100755
index bd16253d..00000000
--- a/chapter11/01-Recursion.js
+++ /dev/null
@@ -1,25 +0,0 @@
-//Recursive solution - DP
-function fibonacci(num){
- if (num === 1 || num === 2){
- return 1;
- }
- if (num > 2){
- return fibonacci(num - 1) + fibonacci(num - 2);
- }
-}
-
-//Non Recursive solution
-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;
-}
-
-console.log(fibonacci(6));
-console.log(fib(6));
\ No newline at end of file
diff --git a/chapter11/02-InfiniteRecursion.html b/chapter11/02-InfiniteRecursion.html
deleted file mode 100755
index e51a8132..00000000
--- a/chapter11/02-InfiniteRecursion.html
+++ /dev/null
@@ -1,10 +0,0 @@
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/chapter11/02-InfiniteRecursion.js b/chapter11/02-InfiniteRecursion.js
deleted file mode 100755
index 2ca26d33..00000000
--- a/chapter11/02-InfiniteRecursion.js
+++ /dev/null
@@ -1,15 +0,0 @@
-var i = 0;
-
-function recursiveFn () {
- i++;
- recursiveFn();
-}
-
-try {
- recursiveFn();
-} catch (ex) {
- alert('i = ' + i + ' error: ' + ex);
-}
-
-//chrome 37 = 20955 RangeError: Maximum call stack size exceeded
-//ff 27 = 343429 InternalError: too much recursion
\ No newline at end of file
diff --git a/chapter11/03-MinCoinChangeDP.html b/chapter11/03-MinCoinChangeDP.html
deleted file mode 100755
index c4171470..00000000
--- a/chapter11/03-MinCoinChangeDP.html
+++ /dev/null
@@ -1,10 +0,0 @@
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/chapter11/03-MinCoinChangeDP.js b/chapter11/03-MinCoinChangeDP.js
deleted file mode 100644
index 90a4a541..00000000
--- a/chapter11/03-MinCoinChangeDP.js
+++ /dev/null
@@ -1,38 +0,0 @@
-function MinCoinChange(coins){
-
- var cache = {};
-
- this.makeChange = function(amount) {
- var me = this;
- if (!amount) {
- return [];
- }
- if (cache[amount]) {
- return cache[amount];
- }
- var min = [], newMin, newAmount;
- for (var i=0; i= 0){
- newMin = me.makeChange(newAmount);
- }
- if (
- newAmount >= 0 &&
- (newMin.length < min.length-1 || !min.length) &&
- (newMin.length || !newAmount)
- ){
- min = [coin].concat(newMin);
- console.log('new Min ' + min + ' for ' + amount);
- }
- }
- return (cache[amount] = min);
- };
-}
-
-
-var minCoinChange = new MinCoinChange([1, 5, 10, 25]);
-console.log(minCoinChange.makeChange(36));
-
-var minCoinChange2 = new MinCoinChange([1, 3, 4]);
-console.log(minCoinChange2.makeChange(6));
\ No newline at end of file
diff --git a/chapter11/04-MinCoinChangeGreedy.html b/chapter11/04-MinCoinChangeGreedy.html
deleted file mode 100755
index cc01ddc2..00000000
--- a/chapter11/04-MinCoinChangeGreedy.html
+++ /dev/null
@@ -1,10 +0,0 @@
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/chapter11/04-MinCoinChangeGreedy.js b/chapter11/04-MinCoinChangeGreedy.js
deleted file mode 100644
index 3050f7ed..00000000
--- a/chapter11/04-MinCoinChangeGreedy.js
+++ /dev/null
@@ -1,25 +0,0 @@
-function MinCoinChange(coins){
-
- var coins = coins;
-
- var cache = {};
-
- this.makeChange = function(amount) {
- var change = [],
- total = 0;
- for (var i=coins.length; i>=0; i--){
- var coin = coins[i];
- while (total + coin <= amount) {
- change.push(coin);
- total += coin;
- }
- }
- return change;
- };
-}
-
-var minCoinChange = new MinCoinChange([1, 5, 10, 25]);
-console.log(minCoinChange.makeChange(36));
-
-var minCoinChange2 = new MinCoinChange([1, 3, 4]);
-console.log(minCoinChange2.makeChange(6));
\ No newline at end of file
diff --git a/chapter11/05-KnapsackProblemDP.html b/chapter11/05-KnapsackProblemDP.html
deleted file mode 100644
index 316f9722..00000000
--- a/chapter11/05-KnapsackProblemDP.html
+++ /dev/null
@@ -1,10 +0,0 @@
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/chapter11/05-KnapsackProblemDP.js b/chapter11/05-KnapsackProblemDP.js
deleted file mode 100644
index fb6adbe7..00000000
--- a/chapter11/05-KnapsackProblemDP.js
+++ /dev/null
@@ -1,53 +0,0 @@
-function knapSack(capacity, weights, values, n) {
-
- var i, w, a, b, kS = [];
-
- for (i = 0; i <= n; i++) {
- kS[i] = [];
- }
-
- for (i = 0; i <= n; i++){
- for (w = 0; w <= capacity; w++){
- if (i == 0 || w == 0){
- kS[i][w] = 0;
-
- } else if (weights[i-1] <= w){
- a = values[i-1] + kS[i-1][w-weights[i-1]];
- b = kS[i-1][w];
- kS[i][w] = (a > b) ? a : b; //max(a,b)
- console.log(a + ' can be part of the solution');
- } else{
- kS[i][w] = kS[i-1][w];
- }
- }
- console.log(kS[i].join());
- }
-
- //extra algorithm to find the items that are part of the solution
- findValues(n, capacity, kS, values, weights);
-
- return kS[n][capacity];
-}
-
-function findValues(n, capacity, kS, weights, values){
- var i=n, k=capacity;
-
- console.log('Items that are part of the solution:');
-
- while (i>0 && k>0){
- if (kS[i][k] !== kS[i-1][k]){
- console.log('item '+i+' can be part of solution w,v: ' + weights[i-1] + ',' + values[i-1]);
- i--;
- k = k - kS[i][k];
- } else {
- i--;
- }
- }
-}
-
-var values = [3,4,5],
- weights = [2,3,4],
- capacity = 5,
- n = values.length;
-
-console.log('Total value that can be carried: ' + knapSack(capacity, weights, values, n));
\ No newline at end of file
diff --git a/chapter11/06-KnapSackProblemRecursive.html b/chapter11/06-KnapSackProblemRecursive.html
deleted file mode 100644
index cc000756..00000000
--- a/chapter11/06-KnapSackProblemRecursive.html
+++ /dev/null
@@ -1,10 +0,0 @@
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/chapter11/06-KnapSackProblemRecursive.js b/chapter11/06-KnapSackProblemRecursive.js
deleted file mode 100644
index 583092e1..00000000
--- a/chapter11/06-KnapSackProblemRecursive.js
+++ /dev/null
@@ -1,22 +0,0 @@
-function knapSack(capacity, weights, values, n) {
-
- if (n == 0 || capacity == 0){
- return 0;
- }
-
- if (weights[n-1] > capacity){
- return knapSack(capacity, weights, values, n-1);
-
- } else {
- var a = values[n-1] + knapSack(capacity-weights[n-1], weights, values, n-1),
- b = knapSack(capacity, weights, values, n-1);
- return (a > b) ? a : b;
- }
-}
-
-var values = [3,4,5],
- weights = [2,3,4],
- capacity = 5,
- n = values.length;
-
-console.log(knapSack(capacity, weights, values, n));
\ No newline at end of file
diff --git a/chapter11/07-KnapSackProblemGreedy.html b/chapter11/07-KnapSackProblemGreedy.html
deleted file mode 100644
index 227d7b4b..00000000
--- a/chapter11/07-KnapSackProblemGreedy.html
+++ /dev/null
@@ -1,10 +0,0 @@
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/chapter11/07-KnapSackProblemGreedy.js b/chapter11/07-KnapSackProblemGreedy.js
deleted file mode 100644
index 4c12e1a6..00000000
--- a/chapter11/07-KnapSackProblemGreedy.js
+++ /dev/null
@@ -1,28 +0,0 @@
-function knapSack(capacity, values, weights) {
- var n = values.length,
- load = 0,
- i = 0,
- val = 0;
-
- for (i=0; i
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/chapter11/08-LongestCommonSubsequenceDP.js b/chapter11/08-LongestCommonSubsequenceDP.js
deleted file mode 100644
index b5eaf3f1..00000000
--- a/chapter11/08-LongestCommonSubsequenceDP.js
+++ /dev/null
@@ -1,105 +0,0 @@
-function lcs(wordX, wordY) {
-
- var m = wordX.length,
- n = wordY.length,
- l = [],
- i, j, a, b;
-
- for (i = 0; i <= m; ++i) {
- l[i] = [];
- for (j = 0; j <= n; ++j) {
- l[i][j] = 0;
- }
- }
-
- for (i=0; i<=m; i++) {
- for (j=0; j<=n; j++) {
- if (i == 0 || j == 0){
- l[i][j] = 0;
-
- } else if (wordX[i-1] == wordY[j-1]) {
- l[i][j] = l[i-1][j-1] + 1;
-
- } else {
- a = l[i-1][j];
- b = l[i][j-1];
- l[i][j] = (a > b) ? a : b; //max(a,b)
- }
- }
- console.log(l[i].join());
- }
-
- return l[m][n];
-}
-
-//complete algorithm that prints the LCS as well
-
-function lcs2(wordX, wordY) {
-
- var m = wordX.length,
- n = wordY.length,
- l = [],
- solution = [],
- i, j, a, b;
-
- for (i = 0; i <= m; ++i) {
- l[i] = [];
- solution[i] = [];
- for (j = 0; j <= n; ++j) {
- l[i][j] = 0;
- solution[i][j] = '0';
- }
- }
-
- for (i=0; i<=m; i++) {
- for (j=0; j<=n; j++) {
- if (i == 0 || j == 0){
- l[i][j] = 0;
-
- } else if (wordX[i-1] == wordY[j-1]) {
- l[i][j] = l[i-1][j-1] + 1;
- solution[i][j] = 'diagonal';
-
- } else {
- a = l[i-1][j];
- b = l[i][j-1];
- l[i][j] = (a > b) ? a : b; //max(a,b)
-
- solution[i][j] = (l[i][j] == l[i - 1][j]) ? 'top' : 'left';
- }
- }
- console.log(l[i].join());
- console.log(solution[i].join());
- }
-
- printSolution(solution, l, wordX, wordY, m, n);
-
- return l[m][n];
-}
-
-function printSolution(solution, l, wordX, wordY, m, n){
-
- var a = m, b = n, i, j,
- x = solution[a][b],
- answer = '';
-
- while (x !== '0') {
- if (solution[a][b] === 'diagonal') {
- answer = wordX[a - 1] + answer;
- a--;
- b--;
- } else if (solution[a][b] === 'left') {
- b--;
- } else if (solution[a][b] === 'top') {
- a--;
- }
- x = solution[a][b];
- }
-
- console.log('lcs: '+ answer);
-}
-
-var wordX = 'acbaed',
- wordY = 'abcadf';
-
-console.log(lcs2(wordX, wordY));
\ No newline at end of file
diff --git a/chapter11/09-LongestCommonSubsequenceRecursive.html b/chapter11/09-LongestCommonSubsequenceRecursive.html
deleted file mode 100644
index 59573751..00000000
--- a/chapter11/09-LongestCommonSubsequenceRecursive.html
+++ /dev/null
@@ -1,10 +0,0 @@
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/chapter11/09-LongestCommonSubsequenceRecursive.js b/chapter11/09-LongestCommonSubsequenceRecursive.js
deleted file mode 100644
index 1c96fab1..00000000
--- a/chapter11/09-LongestCommonSubsequenceRecursive.js
+++ /dev/null
@@ -1,19 +0,0 @@
-function lcs(wordwordX, wordwordY, m, n) {
-
- if (m == 0 || n == 0){
- return 0;
- }
-
- if (wordwordX[m-1] == wordY[n-1]){
- return 1 + lcs(wordX, wordY, m-1, n-1);
- } else {
- var a = lcs(wordX, wordY, m, n-1),
- b = lcs(wordX, wordY, m-1, n);
- return (a > b) ? a : b;
- }
-}
-
-var wordX = 'acbaed',
- wordY = 'abcadf';
-
-console.log(lcs(wordX, wordY, wordX.length, wordY.length));
\ No newline at end of file
diff --git a/chapter11/10-MatrixChainMultiplicationDP.html b/chapter11/10-MatrixChainMultiplicationDP.html
deleted file mode 100644
index 2108a100..00000000
--- a/chapter11/10-MatrixChainMultiplicationDP.html
+++ /dev/null
@@ -1,10 +0,0 @@
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/chapter11/10-MatrixChainMultiplicationDP.js b/chapter11/10-MatrixChainMultiplicationDP.js
deleted file mode 100644
index e335b3cc..00000000
--- a/chapter11/10-MatrixChainMultiplicationDP.js
+++ /dev/null
@@ -1,56 +0,0 @@
-function matrixChainOrder(p, n) {
-
- var i, j, k, l, q,
- m = [], s=[];
-
- for (i = 1; i <= n; i++){
- m[i] = [];
- m[i][i] = 0;
-
- }
-
- for (i = 0; i <= n; i++){ //to help printing the optimal solution
- s[i] = []; //auxiliary
- for (j=0; j<=n; j++){
- s[i][j] = 0;
- }
- }
-
- for (l=2; l
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/chapter11/11-MatrixChainMultiplicationRecursive.js b/chapter11/11-MatrixChainMultiplicationRecursive.js
deleted file mode 100644
index 0b327524..00000000
--- a/chapter11/11-MatrixChainMultiplicationRecursive.js
+++ /dev/null
@@ -1,26 +0,0 @@
-function matrixChainOrder(p, i, j){
-
- if(i == j) {
- return 0;
- }
-
- var k, count,
- min = Number.MAX_SAFE_INTEGER;
-
- for (k = i; k
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/examples/PacktDataStructuresAlgorithms.min.js b/examples/PacktDataStructuresAlgorithms.min.js
new file mode 100644
index 00000000..b7d4c0c6
--- /dev/null
+++ b/examples/PacktDataStructuresAlgorithms.min.js
@@ -0,0 +1,2 @@
+!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("PacktDataStructuresAlgorithms",[],t):"object"==typeof exports?exports.PacktDataStructuresAlgorithms=t():e.PacktDataStructuresAlgorithms=t()}(window,function(){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:r})},n.r=function(e){Object.defineProperty(e,"__esModule",{value:!0})},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=66)}([function(e,t,n){var r,i,o;i=[t],void 0===(o="function"==typeof(r=function(e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.lesserEquals=function(e,n,r){var i=r(e,n);return i===t.LESS_THAN||i===t.EQUALS},e.biggerEquals=function(e,n,r){var i=r(e,n);return i===t.BIGGER_THAN||i===t.EQUALS},e.defaultCompare=function(e,n){return e===n?t.EQUALS:e0&&void 0!==arguments[0]?arguments[0]:n.defaultEquals;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.equalsFn=t,this.count=0,this.head=void 0}return i(e,[{key:"push",value:function(e){var t=new r.Node(e),n=void 0;if(null==this.head)this.head=t;else{for(n=this.head;null!=n.next;)n=n.next;n.next=t}this.count++}},{key:"getElementAt",value:function(e){if(e>=0&&e<=this.count){for(var t=this.head,n=0;n=0&&t<=this.count){var n=new r.Node(e);if(0===t){var i=this.head;n.next=i,this.head=n}else{var o=this.getElementAt(t-1);n.next=o.next,o.next=n}return this.count++,!0}return!1}},{key:"removeAt",value:function(e){if(e>=0&&e1&&(u=function(e,n,r,i){for(var o=e[Math.floor((r+n)/2)],u=n,a=r;u<=a;){for(;i(e[u],o)===t.Compare.LESS_THAN;)u++;for(;i(e[a],o)===t.Compare.BIGGER_THAN;)a--;u<=a&&((0,t.swap)(e,u,a),u++,a--)}return u}(e,r,i,o),r1&&void 0!==arguments[1]?arguments[1]:t.defaultCompare;return n(e,0,e.length-1,r)}})?r.apply(t,i):r)||(e.exports=o)},function(e,t,n){var r,i,o;i=[t,n(0)],void 0===(o="function"==typeof(r=function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.findMaxValue=function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:t.defaultCompare;if(e&&e.length>0){for(var r=e[0],i=1;i1&&void 0!==arguments[1]?arguments[1]:t.defaultCompare;if(e&&e.length>0){for(var r=e[0],i=1;i1&&void 0!==arguments[1]?arguments[1]:t.defaultCompare,r=e.length,i=void 0,o=1;o0&&n(e[u-1],i)===t.Compare.BIGGER_THAN;)e[u]=e[u-1],u--;e[u]=i}return e}})?r.apply(t,i):r)||(e.exports=o)},function(e,t,n){var r,i,o;i=[t],void 0===(o="function"==typeof(r=function(e){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var t=function(){function e(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:n.defaultCompare;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.compareFn=t,this.root=void 0}return i(e,[{key:"insert",value:function(e){null==this.root?this.root=new r.Node(e):this.insertNode(this.root,e)}},{key:"insertNode",value:function(e,t){this.compareFn(t,e.key)===n.Compare.LESS_THAN?null==e.left?e.left=new r.Node(t):this.insertNode(e.left,t):null==e.right?e.right=new r.Node(t):this.insertNode(e.right,t)}},{key:"getRoot",value:function(){return this.root}},{key:"search",value:function(e){return this.searchNode(this.root,e)}},{key:"searchNode",value:function(e,t){return null!=e&&(this.compareFn(t,e.key)===n.Compare.LESS_THAN?this.searchNode(e.left,t):this.compareFn(t,e.key)!==n.Compare.BIGGER_THAN||this.searchNode(e.right,t))}},{key:"inOrderTraverse",value:function(e){this.inOrderTraverseNode(this.root,e)}},{key:"inOrderTraverseNode",value:function(e,t){null!=e&&(this.inOrderTraverseNode(e.left,t),t(e.key),this.inOrderTraverseNode(e.right,t))}},{key:"preOrderTraverse",value:function(e){this.preOrderTraverseNode(this.root,e)}},{key:"preOrderTraverseNode",value:function(e,t){null!=e&&(t(e.key),this.preOrderTraverseNode(e.left,t),this.preOrderTraverseNode(e.right,t))}},{key:"postOrderTraverse",value:function(e){this.postOrderTraverseNode(this.root,e)}},{key:"postOrderTraverseNode",value:function(e,t){null!=e&&(this.postOrderTraverseNode(e.left,t),this.postOrderTraverseNode(e.right,t),t(e.key))}},{key:"min",value:function(){return this.minNode(this.root)}},{key:"minNode",value:function(e){for(var t=e;null!=t&&null!=t.left;)t=t.left;return t}},{key:"max",value:function(){return this.maxNode(this.root)}},{key:"maxNode",value:function(e){for(var t=e;null!=t&&null!=t.right;)t=t.right;return t}},{key:"remove",value:function(e){this.root=this.removeNode(this.root,e)}},{key:"removeNode",value:function(e,t){if(null!=e){if(this.compareFn(t,e.key)===n.Compare.LESS_THAN)return e.left=this.removeNode(e.left,t),e;if(this.compareFn(t,e.key)===n.Compare.BIGGER_THAN)return e.right=this.removeNode(e.right,t),e;if(null==e.left&&null==e.right)return e=void 0;if(null==e.left)return e=e.right;if(null==e.right)return e=e.left;var r=this.minNode(e.right);return e.key=r.key,e.right=this.removeNode(e.right,r.key),e}}}]),e}();t.default=o,e.exports=t.default})?r.apply(t,i):r)||(e.exports=o)},function(e,t,n){var r,i,o;i=[e,t,n(0),n(1)],void 0===(o="function"==typeof(r=function(e,t,n,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:n.defaultToString;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.toStrFn=t,this.table={}}return i(e,[{key:"set",value:function(e,t){if(null!=e&&null!=t){var n=this.toStrFn(e);return this.table[n]=new r.ValuePair(e,t),!0}return!1}},{key:"get",value:function(e){var t=this.table[this.toStrFn(e)];return null==t?void 0:t.value}},{key:"hasKey",value:function(e){return null!=this.table[this.toStrFn(e)]}},{key:"remove",value:function(e){return!!this.hasKey(e)&&(delete this.table[this.toStrFn(e)],!0)}},{key:"values",value:function(){return this.keyValues().map(function(e){return e.value})}},{key:"keys",value:function(){return this.keyValues().map(function(e){return e.key})}},{key:"keyValues",value:function(){return Object.values(this.table)}},{key:"forEach",value:function(e){for(var t=this.keyValues(),n=0;n0&&void 0!==arguments[0]?arguments[0]:n.defaultEquals;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var r=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return r.tail=void 0,r}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),a(t,[{key:"push",value:function(e){var t=new i.DoublyNode(e);null==this.head?(this.head=t,this.tail=t):(this.tail.next=t,t.prev=this.tail,this.tail=t),this.count++}},{key:"insert",value:function(e,t){if(t>=0&&t<=this.count){var n=new i.DoublyNode(e),r=this.head;if(0===t)null==this.head?(this.head=n,this.tail=n):(n.next=this.head,this.head.prev=n,this.head=n);else if(t===this.count)(r=this.tail).next=n,n.prev=r,this.tail=n;else{var o=this.getElementAt(t-1);r=o.next,n.next=r,o.next=n,r.prev=n,n.prev=o}return this.count++,!0}return!1}},{key:"removeAt",value:function(e){if(e>=0&&e0)this.lowestCount--,this.items[this.lowestCount]=e;else{for(var t=this.count;t>0;t--)this.items[t]=this.items[t-1];this.count++,this.items[0]=e}}},{key:"addBack",value:function(e){this.items[this.count]=e,this.count++}},{key:"removeFront",value:function(){if(!this.isEmpty()){var e=this.items[this.lowestCount];return delete this.items[this.lowestCount],this.lowestCount++,e}}},{key:"removeBack",value:function(){if(!this.isEmpty()){this.count--;var e=this.items[this.count];return delete this.items[this.count],e}}},{key:"peekFront",value:function(){if(!this.isEmpty())return this.items[this.lowestCount]}},{key:"peekBack",value:function(){if(!this.isEmpty())return this.items[this.count-1]}},{key:"isEmpty",value:function(){return 0===this.size()}},{key:"clear",value:function(){this.items={},this.count=0,this.lowestCount=0}},{key:"size",value:function(){return this.count-this.lowestCount}},{key:"toString",value:function(){if(this.isEmpty())return"";for(var e=""+this.items[this.lowestCount],t=this.lowestCount+1;t=0&&n>=0&&t1&&void 0!==arguments[1]?arguments[1]:1,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t.length-1;if(n===r)return 0;for(var i=Number.MAX_SAFE_INTEGER,o=n;o2&&void 0!==arguments[2]?arguments[2]:t.length,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:n.length;if(0===r||0===i)return 0;if(t[r-1]===n[i-1])return 1+e(t,n,r-1,i-1);var o=e(t,n,r,i-1),u=e(t,n,r-1,i);return o>u?o:u}})?r.apply(t,i):r)||(e.exports=o)},function(e,t,n){var r,i,o;i=[t],void 0===(o="function"==typeof(r=function(e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.lcs=function(e,t){for(var n=e.length,r=t.length,i=[],o=[],u=0;u<=n;u++){i[u]=[],o[u]=[];for(var a=0;a<=r;a++)i[u][a]=0,o[u][a]="0"}for(var f=0;f<=n;f++)for(var l=0;l<=r;l++)if(0===f||0===l)i[f][l]=0;else if(e[f-1]===t[l-1])i[f][l]=i[f-1][l-1]+1,o[f][l]="diagonal";else{var s=i[f-1][l],c=i[f][l-1];i[f][l]=s>c?s:c,o[f][l]=i[f][l]===i[f-1][l]?"top":"left"}return function(e,t,n,r){for(var i=n,o=r,u=e[i][o],a="";"0"!==u;)"diagonal"===e[i][o]?(a=t[i-1]+a,i--,o--):"left"===e[i][o]?o--:"top"===e[i][o]&&i--,u=e[i][o];return a}(o,e,n,r)}})?r.apply(t,i):r)||(e.exports=o)},function(e,t,n){var r,i,o;i=[t],void 0===(o="function"==typeof(r=function(e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.lcs=function(e,t){for(var n=e.length,r=t.length,i=[],o=0;o<=n;o++){i[o]=[];for(var u=0;u<=r;u++)i[o][u]=0}for(var a=0;a<=n;a++)for(var f=0;f<=r;f++)if(0===a||0===f)i[a][f]=0;else if(e[a-1]===t[f-1])i[a][f]=i[a-1][f-1]+1;else{var l=i[a-1][f],s=i[a][f-1];i[a][f]=l>s?l:s}return i[n][r]}})?r.apply(t,i):r)||(e.exports=o)},function(e,t,n){var r,i,o;i=[t],void 0===(o="function"==typeof(r=function(e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.knapSack=function(e,t,n){for(var r=n.length,i=0,o=0,u=0;ut)return e(t,n,r,i-1);var o=r[i-1]+e(t-n[i-1],n,r,i-1),u=e(t,n,r,i-1);return o>u?o:u}})?r.apply(t,i):r)||(e.exports=o)},function(e,t,n){var r,i,o;i=[t],void 0===(o="function"==typeof(r=function(e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.knapSack=function(e,t,n,r){for(var i=[],o=0;o<=r;o++)i[o]=[];for(var u=0;u<=r;u++)for(var a=0;a<=e;a++)if(0===u||0===a)i[u][a]=0;else if(t[u-1]<=a){var f=n[u-1]+i[u-1][a-t[u-1]],l=i[u-1][a];i[u][a]=f>l?f:l}else i[u][a]=i[u-1][a];return function(e,t,n){for(var r=e,i=t;r>0&&i>0;)n[r][i]!==n[r-1][i]?i-=n[--r][i]:r--}(r,e,i),i[r][e]}})?r.apply(t,i):r)||(e.exports=o)},function(e,t,n){var r,i,o;i=[t],void 0===(o="function"==typeof(r=function(e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.minCoinChange=function(e,t){for(var n=[],r=0,i=e.length;i>=0;i--)for(var o=e[i];r+o<=t;)n.push(o),r+=o;return n}})?r.apply(t,i):r)||(e.exports=o)},function(e,t,n){var r,i,o;i=[t],void 0===(o="function"==typeof(r=function(e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.minCoinChange=function(e,t){var n=[];return function t(r){if(!r)return[];if(n[r])return n[r];for(var i=[],o=void 0,u=void 0,a=0;a=0&&(o=t(u)),u>=0&&(o.length2&&void 0!==arguments[2]?arguments[2]:t.defaultCompare,o=(0,n.quickSort)(e).length-1;return function e(n,r,i,o){var u=arguments.length>4&&void 0!==arguments[4]?arguments[4]:t.defaultCompare;if(i<=o){var a=Math.floor((i+o)/2),f=n[a];return u(f,r)===t.Compare.LESS_THAN?e(n,r,a+1,o,u):u(f,r)===t.Compare.BIGGER_THAN?e(n,r,i,a-1,u):a}return t.DOES_NOT_EXIST}(e,r,0,o,i)}})?r.apply(t,i):r)||(e.exports=o)},function(e,t,n){var r,i,o;i=[t,n(0)],void 0===(o="function"==typeof(r=function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.sequentialSearch=function(e,n){for(var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t.defaultEquals,i=0;i2&&void 0!==arguments[2]?arguments[2]:t.defaultCompare,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:t.defaultEquals,o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:t.defaultDiff,u=0,a=e.length-1,f=-1,l=-1;u<=a&&(0,t.biggerEquals)(n,e[u],r)&&(0,t.lesserEquals)(n,e[a],r);){if(l=o(n,e[u])/o(e[a],e[u]),f=u+Math.floor((a-u)*l),i(e[f],n))return f;r(e[f],n)===t.Compare.LESS_THAN?u=f+1:a=f-1}return t.DOES_NOT_EXIST}})?r.apply(t,i):r)||(e.exports=o)},function(e,t,n){var r,i,o;i=[t,n(0),n(4)],void 0===(o="function"==typeof(r=function(e,t,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.binarySearch=function(e,r){for(var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t.defaultCompare,o=(0,n.quickSort)(e),u=0,a=o.length-1;u<=a;){var f=Math.floor((u+a)/2),l=o[f];if(i(l,r)===t.Compare.LESS_THAN)u=f+1;else{if(i(l,r)!==t.Compare.BIGGER_THAN)return f;a=f-1}}return t.DOES_NOT_EXIST}})?r.apply(t,i):r)||(e.exports=o)},function(e,t,n){var r,i,o;i=[t,n(0)],void 0===(o="function"==typeof(r=function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.shellSort=function(e){for(var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:t.defaultCompare,r=e.length/2;r>0;){for(var i=r;i=r&&n(e[o-r],u)===t.Compare.BIGGER_THAN;)e[o]=e[o-r],o-=r;e[o]=u}r=2===r?1:Math.floor(5*r/11)}return e}})?r.apply(t,i):r)||(e.exports=o)},function(e,t,n){var r,i,o;i=[t,n(0)],void 0===(o="function"==typeof(r=function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.selectionSort=void 0,e.selectionSort=function(e){for(var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:t.defaultCompare,r=e.length,i=void 0,o=0;o1&&void 0!==arguments[1]?arguments[1]:10;if(e.length<2)return e;for(var i=(0,t.findMinValue)(e),o=(0,t.findMaxValue)(e),u=1;(o-i)/u>=1;)e=r(e,n,u,i),u*=n;return e};var n=function(e,t,n,r){return Math.floor((e-t)/n%r)},r=function(e,t,r,i){for(var o=void 0,u=[],a=[],f=0;f=0;c--)o=n(e[c],i,r,t),a[--u[o]]=e[c];for(var h=0;h1&&void 0!==arguments[1]?arguments[1]:t.defaultCompare;if(n.length>1){var i=n,o=i.length,u=Math.floor(o/2),a=e(n.slice(0,u),r),f=e(n.slice(u,o),r);n=function(e,n,r){for(var i=0,o=0,u=[];i0;)e[r++]=n,t--}),e}})?r.apply(t,i):r)||(e.exports=o)},function(e,t,n){var r,i,o;i=[t,n(8)],void 0===(o="function"==typeof(r=function(e,t){"use strict";function n(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t1&&void 0!==arguments[1]?arguments[1]:5;return e.length<2?e:function(e){for(var r=[],i=0;ir&&(r=e[i]);for(var o=Math.floor((r-n)/t)+1,u=[],a=0;a1&&void 0!==arguments[1]?arguments[1]:t.defaultCompare,r=e.length,i=0;i1&&void 0!==arguments[1]?arguments[1]:t.defaultCompare,r=e.length,i=0;i0&&void 0!==arguments[0]&&arguments[0];!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.isDirected=t,this.vertices=[],this.adjList=new i.default}return o(e,[{key:"addVertex",value:function(e){this.vertices.includes(e)||(this.vertices.push(e),this.adjList.set(e,[]))}},{key:"addEdge",value:function(e,t){this.adjList.get(e)||this.addVertex(e),this.adjList.get(t)||this.addVertex(t),this.adjList.get(e).push(t),!0!==this.isDirected&&this.adjList.get(t).push(e)}},{key:"getVertices",value:function(){return this.vertices}},{key:"getAdjList",value:function(){return this.adjList}},{key:"toString",value:function(){for(var e="",t=0;t ";for(var n=this.adjList.get(this.vertices[t]),r=0;r0&&(u=a),f0&&(u=f),u!==t&&((0,n.swap)(e,t,u),r(e,u,i,o))}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:n.defaultCompare,i=e.length;for(!function(e,t){for(var n=Math.floor(e.length/2);n>=0;n-=1)r(e,n,e.length,t)}(e,t);i>1;)(0,n.swap)(e,0,--i),r(e,0,i,t);return e},e.exports=t.default})?r.apply(t,i):r)||(e.exports=o)},function(e,t,n){var r,i,o;i=[t,n(0)],void 0===(o="function"==typeof(r=function(e,t){"use strict";function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.MaxHeap=e.MinHeap=void 0;var r=function(){function e(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:t.defaultCompare;n(this,e),this.compareFn=r,this.heap=[]}return r(e,[{key:"getLeftIndex",value:function(e){return 2*e+1}},{key:"getRightIndex",value:function(e){return 2*e+2}},{key:"getParentIndex",value:function(e){if(0!==e)return Math.floor((e-1)/2)}},{key:"size",value:function(){return this.heap.length}},{key:"isEmpty",value:function(){return this.size()<=0}},{key:"clear",value:function(){this.heap=[]}},{key:"findMinimum",value:function(){return this.isEmpty()?void 0:this.heap[0]}},{key:"insert",value:function(e){if(null!=e){var t=this.heap.length;return this.heap.push(e),this.siftUp(t),!0}return!1}},{key:"siftDown",value:function(e){var n=e,r=this.getLeftIndex(e),i=this.getRightIndex(e),o=this.size();r0&&this.compareFn(this.heap[n],this.heap[e])===t.Compare.BIGGER_THAN;)(0,t.swap)(this.heap,n,e),e=n,n=this.getParentIndex(e)}},{key:"extract",value:function(){if(!this.isEmpty()){if(1===this.size())return this.heap.shift();var e=this.heap[0];return this.heap[0]=this.heap.pop(),this.siftDown(0),e}}},{key:"heapify",value:function(e){e&&(this.heap=e);for(var t=Math.floor(this.size()/2)-1,n=0;n<=t;n++)this.siftDown(n);return this.heap}},{key:"getAsArray",value:function(){return this.heap}}]),e}();e.MaxHeap=function(e){function r(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:t.defaultCompare;n(this,r);var i=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,(r.__proto__||Object.getPrototypeOf(r)).call(this,e));return i.compareFn=e,i.compareFn=(0,t.reverseCompare)(e),i}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(r,e),r}(i)})?r.apply(t,i):r)||(e.exports=o)},function(e,t,n){var r,i,o;i=[e,t,n(0),n(10),n(9)],void 0===(o="function"==typeof(r=function(e,t,n,r,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o,u=(o=r)&&o.__esModule?o:{default:o},a=function(){function e(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:n.defaultCompare;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var r=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return r.compareFn=e,r.root=null,r}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),a(t,[{key:"getNodeHeight",value:function(e){return null==e?-1:Math.max(this.getNodeHeight(e.left),this.getNodeHeight(e.right))+1}},{key:"rotationLL",value:function(e){var t=e.left;return e.left=t.right,t.right=e,t}},{key:"rotationRR",value:function(e){var t=e.right;return e.right=t.left,t.left=e,t}},{key:"rotationLR",value:function(e){return e.left=this.rotationRR(e.left),this.rotationLL(e)}},{key:"rotationRL",value:function(e){return e.right=this.rotationLL(e.right),this.rotationRR(e)}},{key:"getBalanceFactor",value:function(e){var t=this.getNodeHeight(e.left)-this.getNodeHeight(e.right);switch(t){case-2:return f.UNBALANCED_RIGHT;case-1:return f.SLIGHTLY_UNBALANCED_RIGHT;case 1:return f.SLIGHTLY_UNBALANCED_LEFT;case 2:return f.UNBALANCED_LEFT;default:return f.BALANCED}}},{key:"insert",value:function(e){this.root=this.insertNode(this.root,e)}},{key:"insertNode",value:function(e,t){if(null==e)return new i.Node(t);if(this.compareFn(t,e.key)===n.Compare.LESS_THAN)e.left=this.insertNode(e.left,t);else{if(this.compareFn(t,e.key)!==n.Compare.BIGGER_THAN)return e;e.right=this.insertNode(e.right,t)}var r=this.getBalanceFactor(e);if(r===f.UNBALANCED_LEFT){if(this.compareFn(t,e.left.key)!==n.Compare.LESS_THAN)return this.rotationLR(e);e=this.rotationLL(e)}if(r===f.UNBALANCED_RIGHT){if(this.compareFn(t,e.right.key)!==n.Compare.BIGGER_THAN)return this.rotationRL(e);e=this.rotationRR(e)}return e}},{key:"removeNode",value:function(e,n){if(null==(e=function e(t,n,r){null===t&&(t=Function.prototype);var i=Object.getOwnPropertyDescriptor(t,n);if(void 0===i){var o=Object.getPrototypeOf(t);return null===o?void 0:e(o,n,r)}if("value"in i)return i.value;var u=i.get;return void 0!==u?u.call(r):void 0}(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"removeNode",this).call(this,e,n)))return e;var r=this.getBalanceFactor(e);if(r===f.UNBALANCED_LEFT){if(this.getBalanceFactor(e.left)===f.BALANCED||this.getBalanceFactor(e.left)===f.SLIGHTLY_UNBALANCED_LEFT)return this.rotationLL(e);if(this.getBalanceFactor(e.left)===f.SLIGHTLY_UNBALANCED_RIGHT)return this.rotationLR(e.left)}if(r===f.UNBALANCED_RIGHT){if(this.getBalanceFactor(e.right)===f.BALANCED||this.getBalanceFactor(e.right)===f.SLIGHTLY_UNBALANCED_RIGHT)return this.rotationRR(e);if(this.getBalanceFactor(e.right)===f.SLIGHTLY_UNBALANCED_LEFT)return this.rotationRL(e.right)}return e}}]),t}(u.default);t.default=l,e.exports=t.default})?r.apply(t,i):r)||(e.exports=o)},function(e,t,n){var r,i,o;i=[t],void 0===(o="function"==typeof(r=function(e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.fibonacci=function e(t){return t<1?0:t<=2?1:e(t-1)+e(t-2)},e.fibonacciIterative=function(e){if(e<1)return 0;for(var t=0,n=1,r=e,i=2;i<=e;i++)r=n+t,t=n,n=r;return r},e.fibonacciMemoization=function(e){if(e<1)return 0;var t=[0,1];return function e(n){return null!=t[n]?t[n]:t[n]=e(n-1)+e(n-2)}(e)}})?r.apply(t,i):r)||(e.exports=o)},function(e,t,n){var r,i,o;i=[t],void 0===(o="function"==typeof(r=function(e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.factorialIterative=function(e){if(!(e<0)){for(var t=1,n=e;n>1;n--)t*=n;return t}},e.factorial=function e(t){if(!(t<0))return 1===t||0===t?1:t*e(t-1)}})?r.apply(t,i):r)||(e.exports=o)},function(e,t,n){var r,i,o;i=[t,n(1)],void 0===(o="function"==typeof(r=function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.ValuePairLazy=void 0,e.ValuePairLazy=function(e){function t(e,n){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var i=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,n));return i.key=e,i.value=n,i.isDeleted=r,i}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),t}(t.ValuePair)})?r.apply(t,i):r)||(e.exports=o)},function(e,t,n){var r,i,o;i=[e,t,n(0),n(51)],void 0===(o="function"==typeof(r=function(e,t,n,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:n.defaultToString;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.toStrFn=t,this.table={}}return i(e,[{key:"loseloseHashCode",value:function(e){if("number"==typeof e)return e;for(var t=this.toStrFn(e),n=0,r=0;r "+this.table[e[0]].toString()+"}",n=1;n "+this.table[e[n]].toString()+"}";return t}}]),e}();t.default=o,e.exports=t.default})?r.apply(t,i):r)||(e.exports=o)},function(e,t,n){var r,i,o;i=[e,t,n(0),n(1)],void 0===(o="function"==typeof(r=function(e,t,n,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:n.defaultToString;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.toStrFn=t,this.table={}}return i(e,[{key:"loseloseHashCode",value:function(e){if("number"==typeof e)return e;for(var t=this.toStrFn(e),n=0,r=0;r "+this.table[e[0]].toString()+"}",n=1;n "+this.table[e[n]].toString()+"}";return t}}]),e}();t.default=o,e.exports=t.default})?r.apply(t,i):r)||(e.exports=o)},function(e,t,n){var r,i,o;i=[e,t,n(0),n(2),n(1)],void 0===(o="function"==typeof(r=function(e,t,n,r,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o,u=(o=r)&&o.__esModule?o:{default:o},a=function(){function e(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:n.defaultToString;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.toStrFn=t,this.table={}}return a(e,[{key:"loseloseHashCode",value:function(e){if("number"==typeof e)return e;for(var t=this.toStrFn(e),n=0,r=0;r "+this.table[e[0]].toString()+"}",n=1;n "+this.table[e[n]].toString()+"}";return t}}]),e}();t.default=f,e.exports=t.default})?r.apply(t,i):r)||(e.exports=o)},function(e,t,n){var r,i,o;i=[e,t,n(0),n(1)],void 0===(o="function"==typeof(r=function(e,t,n,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:n.defaultToString;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.toStrFn=t,this.table={}}return i(e,[{key:"loseloseHashCode",value:function(e){if("number"==typeof e)return e;for(var t=this.toStrFn(e),n=0,r=0;r "+this.table[e[0]].toString()+"}",n=1;n "+this.table[e[n]].toString()+"}";return t}}]),e}();t.default=o,e.exports=t.default})?r.apply(t,i):r)||(e.exports=o)},function(e,t,n){var r,i,o;i=[e,t],void 0===(o="function"==typeof(r=function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=function(){function e(e,t){for(var n=0;n0&&(o=i,u=r),u.forEach(function(e){o.includes(e)&&n.add(e)}),n}},{key:"difference",value:function(t){var n=new e;return this.values().forEach(function(e){t.has(e)||n.add(e)}),n}},{key:"isSubsetOf",value:function(e){if(this.size()>e.size())return!1;var t=!0;return this.values().every(function(n){return!!e.has(n)||(t=!1,!1)}),t}},{key:"isEmpty",value:function(){return 0===this.size()}},{key:"size",value:function(){return Object.keys(this.items).length}},{key:"clear",value:function(){this.items={}}},{key:"toString",value:function(){if(this.isEmpty())return"";for(var e=this.values(),t=""+e[0],n=1;n0&&void 0!==arguments[0]?arguments[0]:n.defaultEquals,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:n.defaultCompare;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var i=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return i.equalsFn=e,i.compareFn=r,i}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),u(t,[{key:"push",value:function(e){if(this.isEmpty())a(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"push",this).call(this,e);else{var n=this.getIndexNextSortedElement(e);a(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"insert",this).call(this,e,n)}}},{key:"insert",value:function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(this.isEmpty())return a(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"insert",this).call(this,e,0===n?n:0);var r=this.getIndexNextSortedElement(e);return a(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"insert",this).call(this,e,r)}},{key:"getIndexNextSortedElement",value:function(e){for(var t=this.head,r=0;r0&&void 0!==arguments[0]?arguments[0]:n.defaultEquals;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e))}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),a(t,[{key:"push",value:function(e){var t=new i.Node(e);null==this.head?this.head=t:this.getElementAt(this.size()-1).next=t,t.next=this.head,this.count++}},{key:"insert",value:function(e,t){if(t>=0&&t<=this.count){var n=new i.Node(e),r=this.head;if(0===t)null==this.head?(this.head=n,n.next=this.head):(n.next=r,r=this.getElementAt(this.size()),this.head=n,r.next=this.head);else{var o=this.getElementAt(t-1);n.next=o.next,o.next=n}return this.count++,!0}return!1}},{key:"removeAt",value:function(e){if(e>=0&&e1;)if(i=t.removeFront(),o=t.removeBack(),i!==o)return!1;return!0};var n,r=(n=t)&&n.__esModule?n:{default:n}})?r.apply(t,i):r)||(e.exports=o)},function(e,t,n){var r,i,o;i=[t,n(7)],void 0===(o="function"==typeof(r=function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.hotPotato=function(e,t){for(var n=new r.default,i=[],o=0;o1;){for(var u=0;u=0?t.push(o):t.isEmpty()?n=!1:(u=t.pop(),"([{".indexOf(u)!==")]}".indexOf(o)&&(n=!1)),i++;return n&&t.isEmpty()};var n,r=(n=t)&&n.__esModule?n:{default:n}})?r.apply(t,i):r)||(e.exports=o)},function(e,t,n){var r,i,o;i=[t,n(3)],void 0===(o="function"==typeof(r=function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.decimalToBinary=function(e){for(var t=new r.default,n=e,i=void 0,o="";n>0;)i=Math.floor(n%2),t.push(i),n=Math.floor(n/2);for(;!t.isEmpty();)o+=t.pop().toString();return o},e.baseConverter=function(e,t){var n=new r.default,i=e,o=void 0,u="";if(!(t>=2&&t<=36))return"";for(;i>0;)o=Math.floor(i%t),n.push(o),i=Math.floor(i/t);for(;!n.isEmpty();)u+="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[n.pop()];return u};var n,r=(n=t)&&n.__esModule?n:{default:n}})?r.apply(t,i):r)||(e.exports=o)},function(e,t,n){var r,i,o;i=[t,n(3)],void 0===(o="function"==typeof(r=function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.hanoiStack=function(e){for(var t=new r.default,n=new r.default,i=new r.default,o=e;o>0;o--)t.push(o);return function e(t,n,r,i,o,u,a){var f=arguments.length>7&&void 0!==arguments[7]?arguments[7]:[];if(t<=0)return f;if(1===t){i.push(n.pop());var l={};l[o]=n.toString(),l[u]=r.toString(),l[a]=i.toString(),f.push(l)}else{e(t-1,n,i,r,o,a,u,f),i.push(n.pop());var s={};s[o]=n.toString(),s[u]=r.toString(),s[a]=i.toString(),f.push(s),e(t-1,r,n,i,u,o,a,f)}return f}(e,t,i,n,"source","helper","dest")},e.hanoi=function e(t,n,r,i){var o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:[];return t<=0?o:(1===t?o.push([n,i]):(e(t-1,n,i,r,o),o.push([n,i]),e(t-1,r,n,i,o)),o)};var n,r=(n=t)&&n.__esModule?n:{default:n}})?r.apply(t,i):r)||(e.exports=o)},function(e,t,n){var r,i,o;i=[e,t],void 0===(o="function"==typeof(r=function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=function(){function e(e,t){for(var n=0;n compareFn(b, a);\n}\n\nexport function defaultDiff(a, b) {\n return Number(a) - Number(b);\n}\n","export class ValuePair {\n constructor(key, value) {\n this.key = key;\n this.value = value;\n }\n toString() {\n return `[#${this.key}: ${this.value}]`;\n }\n}\n","import { defaultEquals } from '../util';\nimport { Node } from './models/linked-list-models';\n\nexport default class LinkedList {\n constructor(equalsFn = defaultEquals) {\n this.equalsFn = equalsFn;\n this.count = 0;\n this.head = undefined;\n }\n push(element) {\n const node = new Node(element);\n let current;\n if (this.head == null) {\n // catches null && undefined\n this.head = node;\n } else {\n current = this.head;\n while (current.next != null) {\n current = current.next;\n }\n current.next = node;\n }\n this.count++;\n }\n getElementAt(index) {\n if (index >= 0 && index <= this.count) {\n let node = this.head;\n for (let i = 0; i < index && node != null; i++) {\n node = node.next;\n }\n return node;\n }\n return undefined;\n }\n insert(element, index) {\n if (index >= 0 && index <= this.count) {\n const node = new Node(element);\n if (index === 0) {\n const current = this.head;\n node.next = current;\n this.head = node;\n } else {\n const previous = this.getElementAt(index - 1);\n node.next = previous.next;\n previous.next = node;\n }\n this.count++;\n return true;\n }\n return false;\n }\n removeAt(index) {\n if (index >= 0 && index < this.count) {\n let current = this.head;\n if (index === 0) {\n this.head = current.next;\n } else {\n const previous = this.getElementAt(index - 1);\n current = previous.next;\n previous.next = current.next;\n }\n this.count--;\n return current.element;\n }\n return undefined;\n }\n remove(element) {\n const index = this.indexOf(element);\n return this.removeAt(index);\n }\n indexOf(element) {\n let current = this.head;\n for (let i = 0; i < this.size() && current != null; i++) {\n if (this.equalsFn(element, current.element)) {\n return i;\n }\n current = current.next;\n }\n return -1;\n }\n isEmpty() {\n return this.size() === 0;\n }\n size() {\n return this.count;\n }\n getHead() {\n return this.head;\n }\n clear() {\n this.head = undefined;\n this.count = 0;\n }\n toString() {\n if (this.head == null) {\n return '';\n }\n let objString = `${this.head.element}`;\n let current = this.head.next;\n for (let i = 1; i < this.size() && current != null; i++) {\n objString = `${objString},${current.element}`;\n current = current.next;\n }\n return objString;\n }\n}\n","// @ts-check\n\nexport default class Stack {\n constructor() {\n this.count = 0;\n this.items = {};\n }\n push(element) {\n this.items[this.count] = element;\n this.count++;\n }\n pop() {\n if (this.isEmpty()) {\n return undefined;\n }\n this.count--;\n const result = this.items[this.count];\n delete this.items[this.count];\n return result;\n }\n peek() {\n if (this.isEmpty()) {\n return undefined;\n }\n return this.items[this.count - 1];\n }\n isEmpty() {\n return this.count === 0;\n }\n size() {\n return this.count;\n }\n clear() {\n /* while (!this.isEmpty()) {\n this.pop();\n } */\n this.items = {};\n this.count = 0;\n }\n toString() {\n if (this.isEmpty()) {\n return '';\n }\n let objString = `${this.items[0]}`;\n for (let i = 1; i < this.count; i++) {\n objString = `${objString},${this.items[i]}`;\n }\n return objString;\n }\n}\n","import { Compare, defaultCompare, swap } from '../../util';\n\nfunction partition(array, left, right, compareFn) {\n const pivot = array[Math.floor((right + left) / 2)];\n let i = left;\n let j = right;\n\n while (i <= j) {\n while (compareFn(array[i], pivot) === Compare.LESS_THAN) {\n i++;\n }\n while (compareFn(array[j], pivot) === Compare.BIGGER_THAN) {\n j--;\n }\n if (i <= j) {\n swap(array, i, j);\n i++;\n j--;\n }\n }\n return i;\n}\nfunction quick(array, left, right, compareFn) {\n let index;\n if (array.length > 1) {\n index = partition(array, left, right, compareFn);\n if (left < index - 1) {\n quick(array, left, index - 1, compareFn);\n }\n if (index < right) {\n quick(array, index, right, compareFn);\n }\n }\n return array;\n}\nexport function quickSort(array, compareFn = defaultCompare) {\n return quick(array, 0, array.length - 1, compareFn);\n}\n","import { defaultCompare, Compare } from '../../util';\n\nexport function findMaxValue(array, compareFn = defaultCompare) {\n if (array && array.length > 0) {\n let max = array[0];\n for (let i = 1; i < array.length; i++) {\n if (compareFn(max, array[i]) === Compare.LESS_THAN) {\n max = array[i];\n }\n }\n return max;\n }\n return undefined;\n}\nexport function findMinValue(array, compareFn = defaultCompare) {\n if (array && array.length > 0) {\n let min = array[0];\n for (let i = 1; i < array.length; i++) {\n if (compareFn(min, array[i]) === Compare.BIGGER_THAN) {\n min = array[i];\n }\n }\n return min;\n }\n return undefined;\n}\n","export class Node {\n constructor(element, next) {\n this.element = element;\n this.next = next;\n }\n}\nexport class DoublyNode extends Node {\n constructor(element, next, prev) {\n super(element, next);\n this.prev = prev;\n }\n}\n","// @ts-check\n\nexport default class Queue {\n constructor() {\n this.count = 0;\n this.lowestCount = 0;\n this.items = {};\n }\n\n enqueue(element) {\n this.items[this.count] = element;\n this.count++;\n }\n\n dequeue() {\n if (this.isEmpty()) {\n return undefined;\n }\n const result = this.items[this.lowestCount];\n delete this.items[this.lowestCount];\n this.lowestCount++;\n return result;\n }\n\n peek() {\n if (this.isEmpty()) {\n return undefined;\n }\n return this.items[this.lowestCount];\n }\n\n isEmpty() {\n return this.size() === 0;\n }\n\n clear() {\n this.items = {};\n this.count = 0;\n this.lowestCount = 0;\n }\n\n size() {\n return this.count - this.lowestCount;\n }\n\n toString() {\n if (this.isEmpty()) {\n return '';\n }\n let objString = `${this.items[this.lowestCount]}`;\n for (let i = this.lowestCount + 1; i < this.count; i++) {\n objString = `${objString},${this.items[i]}`;\n }\n return objString;\n }\n}\n","import { Compare, defaultCompare } from '../../util';\n\nexport const insertionSort = (array, compareFn = defaultCompare) => {\n const { length } = array;\n let temp;\n for (let i = 1; i < length; i++) {\n let j = i;\n temp = array[i];\n // console.log('to be inserted ' + temp);\n while (j > 0 && compareFn(array[j - 1], temp) === Compare.BIGGER_THAN) {\n // console.log('shift ' + array[j - 1]);\n array[j] = array[j - 1];\n j--;\n }\n // console.log('insert ' + temp);\n array[j] = temp;\n }\n return array;\n};\n","export class Node {\n constructor(key) {\n this.key = key;\n this.left = undefined;\n this.right = undefined;\n }\n toString() {\n return `${this.key}`;\n }\n}\n","import { Compare, defaultCompare } from '../util';\nimport { Node } from './models/node';\n\nexport default class BinarySearchTree {\n constructor(compareFn = defaultCompare) {\n this.compareFn = compareFn;\n this.root = undefined;\n }\n insert(key) {\n // special case: first key\n if (this.root == null) {\n this.root = new Node(key);\n } else {\n this.insertNode(this.root, key);\n }\n }\n insertNode(node, key) {\n if (this.compareFn(key, node.key) === Compare.LESS_THAN) {\n if (node.left == null) {\n node.left = new Node(key);\n } else {\n this.insertNode(node.left, key);\n }\n } else if (node.right == null) {\n node.right = new Node(key);\n } else {\n this.insertNode(node.right, key);\n }\n }\n getRoot() {\n return this.root;\n }\n search(key) {\n return this.searchNode(this.root, key);\n }\n searchNode(node, key) {\n if (node == null) {\n return false;\n }\n if (this.compareFn(key, node.key) === Compare.LESS_THAN) {\n return this.searchNode(node.left, key);\n } else if (this.compareFn(key, node.key) === Compare.BIGGER_THAN) {\n return this.searchNode(node.right, key);\n }\n return true;\n }\n inOrderTraverse(callback) {\n this.inOrderTraverseNode(this.root, callback);\n }\n inOrderTraverseNode(node, callback) {\n if (node != null) {\n this.inOrderTraverseNode(node.left, callback);\n callback(node.key);\n this.inOrderTraverseNode(node.right, callback);\n }\n }\n preOrderTraverse(callback) {\n this.preOrderTraverseNode(this.root, callback);\n }\n preOrderTraverseNode(node, callback) {\n if (node != null) {\n callback(node.key);\n this.preOrderTraverseNode(node.left, callback);\n this.preOrderTraverseNode(node.right, callback);\n }\n }\n postOrderTraverse(callback) {\n this.postOrderTraverseNode(this.root, callback);\n }\n postOrderTraverseNode(node, callback) {\n if (node != null) {\n this.postOrderTraverseNode(node.left, callback);\n this.postOrderTraverseNode(node.right, callback);\n callback(node.key);\n }\n }\n min() {\n return this.minNode(this.root);\n }\n minNode(node) {\n let current = node;\n while (current != null && current.left != null) {\n current = current.left;\n }\n return current;\n }\n max() {\n return this.maxNode(this.root);\n }\n maxNode(node) {\n let current = node;\n while (current != null && current.right != null) {\n current = current.right;\n }\n return current;\n }\n remove(key) {\n this.root = this.removeNode(this.root, key);\n }\n removeNode(node, key) {\n if (node == null) {\n return undefined;\n }\n if (this.compareFn(key, node.key) === Compare.LESS_THAN) {\n node.left = this.removeNode(node.left, key);\n return node;\n } else if (this.compareFn(key, node.key) === Compare.BIGGER_THAN) {\n node.right = this.removeNode(node.right, key);\n return node;\n }\n // key is equal to node.item\n // handle 3 special conditions\n // 1 - a leaf node\n // 2 - a node with only 1 child\n // 3 - a node with 2 children\n // case 1\n if (node.left == null && node.right == null) {\n node = undefined;\n return node;\n }\n // case 2\n if (node.left == null) {\n node = node.right;\n return node;\n } else if (node.right == null) {\n node = node.left;\n return node;\n }\n // case 3\n const aux = this.minNode(node.right);\n node.key = aux.key;\n node.right = this.removeNode(node.right, aux.key);\n return node;\n }\n}\n","import { defaultToString } from '../util';\nimport { ValuePair } from './models/value-pair';\n\nexport default class Dictionary {\n constructor(toStrFn = defaultToString) {\n this.toStrFn = toStrFn;\n this.table = {};\n }\n set(key, value) {\n if (key != null && value != null) {\n const tableKey = this.toStrFn(key);\n this.table[tableKey] = new ValuePair(key, value);\n return true;\n }\n return false;\n }\n get(key) {\n const valuePair = this.table[this.toStrFn(key)];\n return valuePair == null ? undefined : valuePair.value;\n }\n hasKey(key) {\n return this.table[this.toStrFn(key)] != null;\n }\n remove(key) {\n if (this.hasKey(key)) {\n delete this.table[this.toStrFn(key)];\n return true;\n }\n return false;\n }\n values() {\n return this.keyValues().map(valuePair => valuePair.value);\n }\n keys() {\n return this.keyValues().map(valuePair => valuePair.key);\n }\n keyValues() {\n return Object.values(this.table);\n }\n forEach(callbackFn) {\n const valuePairs = this.keyValues();\n for (let i = 0; i < valuePairs.length; i++) {\n const result = callbackFn(valuePairs[i].key, valuePairs[i].value);\n if (result === false) {\n break;\n }\n }\n }\n isEmpty() {\n return this.size() === 0;\n }\n size() {\n return Object.keys(this.table).length;\n }\n clear() {\n this.table = {};\n }\n toString() {\n if (this.isEmpty()) {\n return '';\n }\n const valuePairs = this.keyValues();\n let objString = `${valuePairs[0].toString()}`;\n for (let i = 1; i < valuePairs.length; i++) {\n objString = `${objString},${valuePairs[i].toString()}`;\n }\n return objString;\n }\n}\n","import { defaultEquals } from '../util';\nimport LinkedList from './linked-list';\nimport { DoublyNode } from './models/linked-list-models';\n\nexport default class DoublyLinkedList extends LinkedList {\n constructor(equalsFn = defaultEquals) {\n super(equalsFn);\n this.tail = undefined;\n }\n push(element) {\n const node = new DoublyNode(element);\n if (this.head == null) {\n this.head = node;\n this.tail = node; // NEW\n } else {\n // attach to the tail node // NEW\n this.tail.next = node;\n node.prev = this.tail;\n this.tail = node;\n }\n this.count++;\n }\n insert(element, index) {\n if (index >= 0 && index <= this.count) {\n const node = new DoublyNode(element);\n let current = this.head;\n if (index === 0) {\n if (this.head == null) { // NEW\n this.head = node;\n this.tail = node; // NEW\n } else {\n node.next = this.head;\n this.head.prev = node; // NEW\n this.head = node;\n }\n } else if (index === this.count) { // last item NEW\n current = this.tail;\n current.next = node;\n node.prev = current;\n this.tail = node;\n } else {\n const previous = this.getElementAt(index - 1);\n current = previous.next;\n node.next = current;\n previous.next = node;\n current.prev = node; // NEW\n node.prev = previous; // NEW\n }\n this.count++;\n return true;\n }\n return false;\n }\n removeAt(index) {\n if (index >= 0 && index < this.count) {\n let current = this.head;\n if (index === 0) {\n this.head = this.head.next;\n // if there is only one item, then we update tail as well //NEW\n if (this.count === 1) {\n // {2}\n this.tail = undefined;\n } else {\n this.head.prev = undefined;\n }\n } else if (index === this.count - 1) {\n // last item //NEW\n current = this.tail;\n this.tail = current.prev;\n this.tail.next = undefined;\n } else {\n current = this.getElementAt(index);\n const previous = current.prev;\n // link previous with current's next - skip it to remove\n previous.next = current.next;\n current.next.prev = previous; // NEW\n }\n this.count--;\n return current.element;\n }\n return undefined;\n }\n indexOf(element) {\n let current = this.head;\n let index = 0;\n while (current != null) {\n if (this.equalsFn(element, current.element)) {\n return index;\n }\n index++;\n current = current.next;\n }\n return -1;\n }\n getHead() {\n return this.head;\n }\n getTail() {\n return this.tail;\n }\n clear() {\n super.clear();\n this.tail = undefined;\n }\n toString() {\n if (this.head == null) {\n return '';\n }\n let objString = `${this.head.element}`;\n let current = this.head.next;\n while (current != null) {\n objString = `${objString},${current.element}`;\n current = current.next;\n }\n return objString;\n }\n inverseToString() {\n if (this.tail == null) {\n return '';\n }\n let objString = `${this.tail.element}`;\n let previous = this.tail.prev;\n while (previous != null) {\n objString = `${objString},${previous.element}`;\n previous = previous.prev;\n }\n return objString;\n }\n}\n","// @ts-check\n\nexport default class Deque {\n constructor() {\n this.count = 0;\n this.lowestCount = 0;\n this.items = {};\n }\n\n addFront(element) {\n if (this.isEmpty()) {\n this.addBack(element);\n } else if (this.lowestCount > 0) {\n this.lowestCount--;\n this.items[this.lowestCount] = element;\n } else {\n for (let i = this.count; i > 0; i--) {\n this.items[i] = this.items[i - 1];\n }\n this.count++;\n this.items[0] = element;\n }\n }\n\n addBack(element) {\n this.items[this.count] = element;\n this.count++;\n }\n\n removeFront() {\n if (this.isEmpty()) {\n return undefined;\n }\n const result = this.items[this.lowestCount];\n delete this.items[this.lowestCount];\n this.lowestCount++;\n return result;\n }\n\n removeBack() {\n if (this.isEmpty()) {\n return undefined;\n }\n this.count--;\n const result = this.items[this.count];\n delete this.items[this.count];\n return result;\n }\n\n peekFront() {\n if (this.isEmpty()) {\n return undefined;\n }\n return this.items[this.lowestCount];\n }\n\n peekBack() {\n if (this.isEmpty()) {\n return undefined;\n }\n return this.items[this.count - 1];\n }\n\n isEmpty() {\n return this.size() === 0;\n }\n\n clear() {\n this.items = {};\n this.count = 0;\n this.lowestCount = 0;\n }\n\n size() {\n return this.count - this.lowestCount;\n }\n\n toString() {\n if (this.isEmpty()) {\n return '';\n }\n let objString = `${this.items[this.lowestCount]}`;\n for (let i = this.lowestCount + 1; i < this.count; i++) {\n objString = `${objString},${this.items[i]}`;\n }\n return objString;\n }\n}\n","export const floydWarshall = graph => {\n const dist = [];\n const { length } = graph;\n for (let i = 0; i < length; i++) {\n dist[i] = [];\n for (let j = 0; j < length; j++) {\n if (i === j) {\n dist[i][j] = 0;\n } else if (!isFinite(graph[i][j])) {\n dist[i][j] = Infinity;\n } else {\n dist[i][j] = graph[i][j];\n }\n }\n }\n for (let k = 0; k < length; k++) {\n for (let i = 0; i < length; i++) {\n for (let j = 0; j < length; j++) {\n if (dist[i][k] + dist[k][j] < dist[i][j]) {\n dist[i][j] = dist[i][k] + dist[k][j];\n }\n }\n }\n }\n return dist;\n};\n","const UNASSIGNED = 0;\n\nfunction usedInRow(matrix, row, num) {\n for (let col = 0; col < matrix.length; col++) {\n if (matrix[row][col] === num) {\n return true;\n }\n }\n return false;\n}\n\nfunction usedInCol(matrix, col, num) {\n for (let row = 0; row < matrix.length; row++) {\n if (matrix[row][col] === num) {\n return true;\n }\n }\n return false;\n}\n\nfunction usedInBox(matrix, boxStartRow, boxStartCol, num) {\n for (let row = 0; row < 3; row++) {\n for (let col = 0; col < 3; col++) {\n if (matrix[row + boxStartRow][col + boxStartCol] === num) {\n return true;\n }\n }\n }\n return false;\n}\n\nfunction isSafe(matrix, row, col, num) {\n return (\n !usedInRow(matrix, row, num) &&\n !usedInCol(matrix, col, num) &&\n !usedInBox(matrix, row - (row % 3), col - (col % 3), num)\n );\n}\nfunction solveSudoku(matrix) {\n let row = 0;\n let col = 0;\n let checkBlankSpaces = false;\n\n for (row = 0; row < matrix.length; row++) {\n for (col = 0; col < matrix[row].length; col++) {\n if (matrix[row][col] === UNASSIGNED) {\n checkBlankSpaces = true;\n break;\n }\n }\n if (checkBlankSpaces === true) {\n break;\n }\n }\n if (checkBlankSpaces === false) {\n return true;\n }\n\n for (let num = 1; num <= 9; num++) {\n if (isSafe(matrix, row, col, num)) {\n matrix[row][col] = num;\n if (solveSudoku(matrix)) {\n return true;\n }\n matrix[row][col] = UNASSIGNED;\n }\n }\n return false;\n}\n\nexport function sudokuSolver(matrix) {\n if (solveSudoku(matrix) === true) {\n return matrix;\n }\n return 'NO SOLUTION EXISTS!';\n}\n","function isSafe(maze, x, y) {\n const n = maze.length;\n if (x >= 0 && y >= 0 && x < n && y < n && maze[x][y] !== 0) {\n return true;\n }\n return false;\n}\n\nfunction findPath(maze, x, y, solution) {\n const n = maze.length;\n if (x === n - 1 && y === n - 1) {\n solution[x][y] = 1;\n return true;\n }\n if (isSafe(maze, x, y) === true) {\n solution[x][y] = 1;\n if (findPath(maze, x + 1, y, solution)) {\n return true;\n }\n if (findPath(maze, x, y + 1, solution)) {\n return true;\n }\n solution[x][y] = 0;\n return false;\n }\n return false;\n}\n\nexport function ratInAMaze(maze) {\n const solution = [];\n for (let i = 0; i < maze.length; i++) {\n solution[i] = [];\n for (let j = 0; j < maze[i].length; j++) {\n solution[i][j] = 0;\n }\n }\n if (findPath(maze, 0, 0, solution) === true) {\n return solution;\n }\n return 'NO PATH FOUND';\n}\n","export function matrixChainOrder(p, i = 1, j = p.length - 1) {\n if (i === j) {\n return 0;\n }\n let min = Number.MAX_SAFE_INTEGER;\n for (let k = i; k < j; k++) {\n const count =\n matrixChainOrder(p, i, k) + matrixChainOrder(p, k + 1, j) + ((p[i - 1] * p[k]) * p[j]);\n if (count < min) {\n min = count;\n }\n }\n return min;\n}\n","function printOptimalParenthesis(s, i, j) {\n if (i === j) {\n // console.log('A[' + i + ']');\n } else {\n // console.log('(');\n printOptimalParenthesis(s, i, s[i][j]);\n printOptimalParenthesis(s, s[i][j] + 1, j);\n // console.log(')');\n }\n}\n\nexport function matrixChainOrder(p) {\n const n = p.length;\n const m = [];\n const s = [];\n for (let i = 1; i <= n; i++) {\n m[i] = [];\n m[i][i] = 0;\n }\n for (let i = 0; i <= n; i++) {\n // to help printing the optimal solution\n s[i] = []; // auxiliary\n for (let j = 0; j <= n; j++) {\n s[i][j] = 0;\n }\n }\n for (let l = 2; l < n; l++) {\n for (let i = 1; i <= (n - l) + 1; i++) {\n const j = (i + l) - 1;\n m[i][j] = Number.MAX_SAFE_INTEGER;\n for (let k = i; k <= j - 1; k++) {\n // q = cost/scalar multiplications\n const q = m[i][k] + m[k + 1][j] + ((p[i - 1] * p[k]) * p[j]);\n if (q < m[i][j]) {\n m[i][j] = q;\n s[i][j] = k; // s[i,j] = Second auxiliary table that stores k\n }\n }\n }\n }\n // console.log(m);\n // console.log(s);\n printOptimalParenthesis(s, 1, n - 1);\n return m[1][n - 1];\n}\n\n","export function lcs(wordX, wordY, m = wordX.length, n = wordY.length) {\n if (m === 0 || n === 0) {\n return 0;\n }\n if (wordX[m - 1] === wordY[n - 1]) {\n return 1 + lcs(wordX, wordY, m - 1, n - 1);\n }\n const a = lcs(wordX, wordY, m, n - 1);\n const b = lcs(wordX, wordY, m - 1, n);\n return a > b ? a : b;\n}\n","function printSolution(solution, wordX, m, n) {\n let a = m;\n let b = n;\n let x = solution[a][b];\n let answer = '';\n while (x !== '0') {\n if (solution[a][b] === 'diagonal') {\n answer = wordX[a - 1] + answer;\n a--;\n b--;\n } else if (solution[a][b] === 'left') {\n b--;\n } else if (solution[a][b] === 'top') {\n a--;\n }\n x = solution[a][b];\n }\n return answer;\n}\nexport function lcs(wordX, wordY) {\n const m = wordX.length;\n const n = wordY.length;\n const l = [];\n const solution = [];\n for (let i = 0; i <= m; i++) {\n l[i] = [];\n solution[i] = [];\n for (let j = 0; j <= n; j++) {\n l[i][j] = 0;\n solution[i][j] = '0';\n }\n }\n for (let i = 0; i <= m; i++) {\n for (let j = 0; j <= n; j++) {\n if (i === 0 || j === 0) {\n l[i][j] = 0;\n } else if (wordX[i - 1] === wordY[j - 1]) {\n l[i][j] = l[i - 1][j - 1] + 1;\n solution[i][j] = 'diagonal';\n } else {\n const a = l[i - 1][j];\n const b = l[i][j - 1];\n l[i][j] = a > b ? a : b; // max(a,b)\n solution[i][j] = l[i][j] === l[i - 1][j] ? 'top' : 'left';\n }\n }\n // console.log(l[i].join());\n // console.log(solution[i].join());\n }\n return printSolution(solution, wordX, m, n);\n}\n","export function lcs(wordX, wordY) {\n const m = wordX.length;\n const n = wordY.length;\n const l = [];\n for (let i = 0; i <= m; i++) {\n l[i] = [];\n for (let j = 0; j <= n; j++) {\n l[i][j] = 0;\n }\n }\n for (let i = 0; i <= m; i++) {\n for (let j = 0; j <= n; j++) {\n if (i === 0 || j === 0) {\n l[i][j] = 0;\n } else if (wordX[i - 1] === wordY[j - 1]) {\n l[i][j] = l[i - 1][j - 1] + 1;\n } else {\n const a = l[i - 1][j];\n const b = l[i][j - 1];\n l[i][j] = a > b ? a : b; // max(a,b)\n }\n }\n // console.log(l[i].join());\n }\n return l[m][n];\n}\n","export function knapSack(capacity, weights, values) {\n const n = values.length;\n let load = 0;\n let val = 0;\n for (let i = 0; i < n && load < capacity; i++) {\n if (weights[i] <= capacity - load) {\n val += values[i];\n load += weights[i];\n // console.log('using item ' + (i + 1) + ' for the solution');\n } else {\n const r = (capacity - load) / weights[i];\n val += r * values[i];\n load += weights[i];\n // console.log('using ratio of ' + r + ' for item ' + (i + 1) + ' for the solution');\n }\n }\n return val;\n}\n","export function knapSack(capacity, weights, values, n) {\n if (n === 0 || capacity === 0) {\n return 0;\n }\n if (weights[n - 1] > capacity) {\n return knapSack(capacity, weights, values, n - 1);\n }\n const a = values[n - 1] + knapSack(capacity - weights[n - 1], weights, values, n - 1);\n const b = knapSack(capacity, weights, values, n - 1);\n return a > b ? a : b;\n}\n","function findValues(n, capacity, kS) {\n let i = n;\n let k = capacity;\n // console.log('Items that are part of the solution:');\n while (i > 0 && k > 0) {\n if (kS[i][k] !== kS[i - 1][k]) {\n // console.log(\n // item ' + i + ' can be part of solution w,v: ' + weights[i - 1] + ',' + values[i - 1]\n // );\n i--;\n k -= kS[i][k];\n } else {\n i--;\n }\n }\n}\n\nexport function knapSack(capacity, weights, values, n) {\n const kS = [];\n for (let i = 0; i <= n; i++) {\n kS[i] = [];\n }\n for (let i = 0; i <= n; i++) {\n for (let w = 0; w <= capacity; w++) {\n if (i === 0 || w === 0) {\n kS[i][w] = 0;\n } else if (weights[i - 1] <= w) {\n const a = values[i - 1] + kS[i - 1][w - weights[i - 1]];\n const b = kS[i - 1][w];\n kS[i][w] = a > b ? a : b; // max(a,b)\n // console.log(a + ' can be part of the solution');\n } else {\n kS[i][w] = kS[i - 1][w];\n }\n }\n // console.log(kS[i].join());\n }\n // extra algorithm to find the items that are part of the solution\n findValues(n, capacity, kS);\n return kS[n][capacity];\n}\n","export function minCoinChange(coins, amount) {\n const change = [];\n let total = 0;\n for (let i = coins.length; i >= 0; i--) {\n const coin = coins[i];\n while (total + coin <= amount) {\n change.push(coin);\n total += coin;\n }\n }\n return change;\n}\n","export function minCoinChange(coins, amount) {\n const cache = [];\n\n const makeChange = (value) => {\n if (!value) {\n return [];\n }\n if (cache[value]) {\n return cache[value];\n }\n let min = [];\n let newMin;\n let newAmount;\n for (let i = 0; i < coins.length; i++) {\n const coin = coins[i];\n newAmount = value - coin;\n if (newAmount >= 0) {\n newMin = makeChange(newAmount);\n }\n if (\n newAmount >= 0 &&\n (newMin.length < min.length - 1 || !min.length) &&\n (newMin.length || !newAmount)\n ) {\n min = [coin].concat(newMin);\n // console.log('new Min ' + min + ' for ' + amount);\n }\n }\n return (cache[value] = min);\n };\n return makeChange(amount);\n}\n","import { Compare, defaultCompare, DOES_NOT_EXIST } from '../../util';\nimport { quickSort } from '../sorting/quicksort';\n\nfunction binarySearchRecursive(array, value, low, high, compareFn = defaultCompare) {\n if (low <= high) {\n const mid = Math.floor((low + high) / 2);\n const element = array[mid];\n if (compareFn(element, value) === Compare.LESS_THAN) {\n return binarySearchRecursive(array, value, mid + 1, high, compareFn);\n }\n if (compareFn(element, value) === Compare.BIGGER_THAN) {\n return binarySearchRecursive(array, value, low, mid - 1, compareFn);\n }\n return mid;\n }\n return DOES_NOT_EXIST;\n}\n\nexport function binarySearch(array, value, compareFn = defaultCompare) {\n const sortedArray = quickSort(array);\n const low = 0;\n const high = sortedArray.length - 1;\n return binarySearchRecursive(array, value, low, high, compareFn);\n}\n","import { defaultEquals, DOES_NOT_EXIST } from '../../util';\n\nexport function sequentialSearch(array, value, equalsFn = defaultEquals) {\n for (let i = 0; i < array.length; i++) {\n if (equalsFn(value, array[i])) {\n return i;\n }\n }\n return DOES_NOT_EXIST;\n}\n","import {\n biggerEquals,\n Compare,\n defaultCompare,\n defaultEquals,\n defaultDiff,\n DOES_NOT_EXIST,\n lesserEquals\n} from '../../util';\n\nexport function interpolationSearch(\n array,\n value,\n compareFn = defaultCompare,\n equalsFn = defaultEquals,\n diffFn = defaultDiff\n) {\n const { length } = array;\n let low = 0;\n let high = length - 1;\n let position = -1;\n let delta = -1;\n while (\n low <= high &&\n biggerEquals(value, array[low], compareFn) &&\n lesserEquals(value, array[high], compareFn)\n ) {\n delta = diffFn(value, array[low]) / diffFn(array[high], array[low]);\n position = low + Math.floor((high - low) * delta);\n if (equalsFn(array[position], value)) {\n return position;\n }\n if (compareFn(array[position], value) === Compare.LESS_THAN) {\n low = position + 1;\n } else {\n high = position - 1;\n }\n }\n return DOES_NOT_EXIST;\n}\n","import { Compare, defaultCompare, DOES_NOT_EXIST } from '../../util';\nimport { quickSort } from '../sorting/quicksort';\n\nexport function binarySearch(array, value, compareFn = defaultCompare) {\n const sortedArray = quickSort(array);\n let low = 0;\n let high = sortedArray.length - 1;\n while (low <= high) {\n const mid = Math.floor((low + high) / 2);\n const element = sortedArray[mid];\n // console.log('mid element is ' + element);\n if (compareFn(element, value) === Compare.LESS_THAN) {\n low = mid + 1;\n // console.log('low is ' + low);\n } else if (compareFn(element, value) === Compare.BIGGER_THAN) {\n high = mid - 1;\n // console.log('high is ' + high);\n } else {\n // console.log('found it');\n return mid;\n }\n }\n return DOES_NOT_EXIST;\n}\n","import { Compare, defaultCompare } from '../../util';\n\nexport function shellSort(array, compareFn = defaultCompare) {\n let increment = array.length / 2;\n while (increment > 0) {\n for (let i = increment; i < array.length; i++) {\n let j = i;\n const temp = array[i];\n while (j >= increment && compareFn(array[j - increment], temp) === Compare.BIGGER_THAN) {\n array[j] = array[j - increment];\n j -= increment;\n }\n array[j] = temp;\n }\n if (increment === 2) {\n increment = 1;\n } else {\n increment = Math.floor((increment * 5) / 11);\n }\n }\n return array;\n}\n","import { Compare, defaultCompare, swap } from '../../util';\n\nexport const selectionSort = (array, compareFn = defaultCompare) => {\n const { length } = array;\n let indexMin;\n for (let i = 0; i < length - 1; i++) {\n indexMin = i;\n // console.log('index ' + array[i]);\n for (let j = i; j < length; j++) {\n if (compareFn(array[indexMin], array[j]) === Compare.BIGGER_THAN) {\n // console.log('new index min ' + array[j]);\n indexMin = j;\n }\n }\n if (i !== indexMin) {\n // console.log('swap ' + array[i] + ' with ' + array[indexMin]);\n swap(array, i, indexMin);\n }\n }\n return array;\n};\n","import { findMaxValue, findMinValue } from '../search/min-max-search';\n\nconst getBucketIndex = (value, minValue, significantDigit, radixBase) =>\n Math.floor(((value - minValue) / significantDigit) % radixBase);\n\nconst countingSortForRadix = (array, radixBase, significantDigit, minValue) => {\n let bucketsIndex;\n const buckets = [];\n const aux = [];\n for (let i = 0; i < radixBase; i++) {\n buckets[i] = 0;\n }\n for (let i = 0; i < array.length; i++) {\n bucketsIndex = getBucketIndex(array[i], minValue, significantDigit, radixBase);\n buckets[bucketsIndex]++;\n }\n for (let i = 1; i < radixBase; i++) {\n buckets[i] += buckets[i - 1];\n }\n for (let i = array.length - 1; i >= 0; i--) {\n bucketsIndex = getBucketIndex(array[i], minValue, significantDigit, radixBase);\n aux[--buckets[bucketsIndex]] = array[i];\n }\n for (let i = 0; i < array.length; i++) {\n array[i] = aux[i];\n }\n return array;\n};\nexport function radixSort(array, radixBase = 10) {\n if (array.length < 2) {\n return array;\n }\n const minValue = findMinValue(array);\n const maxValue = findMaxValue(array);\n // Perform counting sort for each significant digit, starting at 1\n let significantDigit = 1;\n while ((maxValue - minValue) / significantDigit >= 1) {\n // console.log('radix sort for digit ' + significantDigit);\n array = countingSortForRadix(array, radixBase, significantDigit, minValue);\n // console.log(array.join());\n significantDigit *= radixBase;\n }\n return array;\n}\n","import { Compare, defaultCompare } from '../../util';\n\nfunction merge(left, right, compareFn) {\n let i = 0;\n let j = 0;\n const result = [];\n while (i < left.length && j < right.length) {\n result.push(compareFn(left[i], right[j]) === Compare.LESS_THAN ? left[i++] : right[j++]);\n }\n return result.concat(i < left.length ? left.slice(i) : right.slice(j));\n}\nexport function mergeSort(array, compareFn = defaultCompare) {\n if (array.length > 1) {\n const { length } = array;\n const middle = Math.floor(length / 2);\n const left = mergeSort(array.slice(0, middle), compareFn);\n const right = mergeSort(array.slice(middle, length), compareFn);\n array = merge(left, right, compareFn);\n }\n return array;\n}\n","import { findMaxValue } from '../search/min-max-search';\n\nexport function countingSort(array) {\n if (array.length < 2) {\n return array;\n }\n const maxValue = findMaxValue(array);\n let sortedIndex = 0;\n const counts = new Array(maxValue + 1);\n array.forEach(element => {\n if (!counts[element]) {\n counts[element] = 0;\n }\n counts[element]++;\n });\n // console.log('Frequencies: ' + counts.join());\n counts.forEach((element, i) => {\n while (element > 0) {\n array[sortedIndex++] = i;\n element--;\n }\n });\n return array;\n}\n","import { insertionSort } from './insertion-sort';\n\nfunction createBuckets(array, bucketSize) {\n let minValue = array[0];\n let maxValue = array[0];\n for (let i = 1; i < array.length; i++) {\n if (array[i] < minValue) {\n minValue = array[i];\n } else if (array[i] > maxValue) {\n maxValue = array[i];\n }\n }\n const bucketCount = Math.floor((maxValue - minValue) / bucketSize) + 1;\n const buckets = [];\n for (let i = 0; i < bucketCount; i++) {\n buckets[i] = [];\n }\n for (let i = 0; i < array.length; i++) {\n buckets[Math.floor((array[i] - minValue) / bucketSize)].push(array[i]);\n }\n return buckets;\n}\nfunction sortBuckets(buckets) {\n const sortedArray = [];\n for (let i = 0; i < buckets.length; i++) {\n if (buckets[i] != null) {\n insertionSort(buckets[i]);\n sortedArray.push(...buckets[i]);\n }\n }\n return sortedArray;\n}\nexport function bucketSort(array, bucketSize = 5) {\n if (array.length < 2) {\n return array;\n }\n const buckets = createBuckets(array, bucketSize);\n return sortBuckets(buckets);\n}\n","import { Compare, defaultCompare, swap } from '../../util';\n\nexport function modifiedBubbleSort(array, compareFn = defaultCompare) {\n const { length } = array;\n for (let i = 0; i < length; i++) {\n // console.log('--- ');\n for (let j = 0; j < length - 1 - i; j++) {\n // console.log('compare ' + array[j] + ' with ' + array[j + 1]);\n if (compareFn(array[j], array[j + 1]) === Compare.BIGGER_THAN) {\n // console.log('swap ' + array[j] + ' with ' + array[j + 1]);\n swap(array, j, j + 1);\n }\n }\n }\n return array;\n}\n","import { Compare, defaultCompare, swap } from '../../util';\n\nexport function bubbleSort(array, compareFn = defaultCompare) {\n const { length } = array;\n for (let i = 0; i < length; i++) {\n // console.log('--- ');\n for (let j = 0; j < length - 1; j++) {\n // console.log('compare ' + array[j] + ' with ' + array[j + 1]);\n if (compareFn(array[j], array[j + 1]) === Compare.BIGGER_THAN) {\n // console.log('swap ' + array[j] + ' with ' + array[j + 1]);\n swap(array, j, j + 1);\n }\n }\n }\n return array;\n}\n","import { swap } from '../../util';\n\nexport function shuffle(array) {\n let currentIndex = array.length;\n while (currentIndex !== 0) {\n const randomIndex = Math.floor(Math.random() * currentIndex);\n currentIndex--;\n swap(array, currentIndex, randomIndex);\n }\n return array;\n}\n","const INF = Number.MAX_SAFE_INTEGER;\nconst find = (i, parent) => {\n while (parent[i]) {\n i = parent[i]; // eslint-disable-line prefer-destructuring\n }\n return i;\n};\nconst union = (i, j, parent) => {\n if (i !== j) {\n parent[j] = i;\n return true;\n }\n return false;\n};\nconst initializeCost = graph => {\n const cost = [];\n const { length } = graph;\n for (let i = 0; i < length; i++) {\n cost[i] = [];\n for (let j = 0; j < length; j++) {\n if (graph[i][j] === 0) {\n cost[i][j] = INF;\n } else {\n cost[i][j] = graph[i][j];\n }\n }\n }\n return cost;\n};\nexport const kruskal = graph => {\n const { length } = graph;\n const parent = [];\n let ne = 0;\n let a;\n let b;\n let u;\n let v;\n const cost = initializeCost(graph);\n while (ne < length - 1) {\n for (let i = 0, min = INF; i < length; i++) {\n for (let j = 0; j < length; j++) {\n if (cost[i][j] < min) {\n min = cost[i][j];\n a = u = i;\n b = v = j;\n }\n }\n }\n u = find(u, parent);\n v = find(v, parent);\n if (union(u, v, parent)) {\n ne++;\n }\n cost[a][b] = cost[b][a] = INF;\n }\n return parent;\n};\n","const INF = Number.MAX_SAFE_INTEGER;\nconst minKey = (graph, key, visited) => {\n // Initialize min value\n let min = INF;\n let minIndex = 0;\n for (let v = 0; v < graph.length; v++) {\n if (visited[v] === false && key[v] < min) {\n min = key[v];\n minIndex = v;\n }\n }\n return minIndex;\n};\nexport const prim = graph => {\n const parent = [];\n const key = [];\n const visited = [];\n const { length } = graph;\n for (let i = 0; i < length; i++) {\n key[i] = INF;\n visited[i] = false;\n }\n key[0] = 0;\n parent[0] = -1;\n for (let i = 0; i < length - 1; i++) {\n const u = minKey(graph, key, visited);\n visited[u] = true;\n for (let v = 0; v < length; v++) {\n if (graph[u][v] && !visited[v] && graph[u][v] < key[v]) {\n parent[v] = u;\n key[v] = graph[u][v];\n }\n }\n }\n return parent;\n};\n","const INF = Number.MAX_SAFE_INTEGER;\nconst minDistance = (dist, visited) => {\n let min = INF;\n let minIndex = -1;\n for (let v = 0; v < dist.length; v++) {\n if (visited[v] === false && dist[v] <= min) {\n min = dist[v];\n minIndex = v;\n }\n }\n return minIndex;\n};\nexport const dijkstra = (graph, src) => {\n const dist = [];\n const visited = [];\n const { length } = graph;\n for (let i = 0; i < length; i++) {\n dist[i] = INF;\n visited[i] = false;\n }\n dist[src] = 0;\n for (let i = 0; i < length - 1; i++) {\n const u = minDistance(dist, visited);\n visited[u] = true;\n for (let v = 0; v < length; v++) {\n if (!visited[v] && graph[u][v] !== 0 && dist[u] !== INF && dist[u] + graph[u][v] < dist[v]) {\n dist[v] = dist[u] + graph[u][v];\n }\n }\n }\n return dist;\n};\n","// import Graph from '../../data-structures/graph';\n\nconst Colors = {\n WHITE: 0,\n GREY: 1,\n BLACK: 2\n};\n\nconst initializeColor = vertices => {\n const color = {};\n for (let i = 0; i < vertices.length; i++) {\n color[vertices[i]] = Colors.WHITE;\n }\n return color;\n};\n\nconst depthFirstSearchVisit = (u, color, adjList, callback) => {\n color[u] = Colors.GREY;\n if (callback) {\n callback(u);\n }\n // console.log('Discovered ' + u);\n const neighbors = adjList.get(u);\n for (let i = 0; i < neighbors.length; i++) {\n const w = neighbors[i];\n if (color[w] === Colors.WHITE) {\n depthFirstSearchVisit(w, color, adjList, callback);\n }\n }\n color[u] = Colors.BLACK;\n // console.log('explored ' + u);\n};\n\nexport const depthFirstSearch = (graph, callback) => {\n const vertices = graph.getVertices();\n const adjList = graph.getAdjList();\n const color = initializeColor(vertices);\n\n for (let i = 0; i < vertices.length; i++) {\n if (color[vertices[i]] === Colors.WHITE) {\n depthFirstSearchVisit(vertices[i], color, adjList, callback);\n }\n }\n};\n\nconst DFSVisit = (u, color, d, f, p, time, adjList) => {\n // console.log('discovered ' + u);\n color[u] = Colors.GREY;\n d[u] = ++time.count;\n const neighbors = adjList.get(u);\n for (let i = 0; i < neighbors.length; i++) {\n const w = neighbors[i];\n if (color[w] === Colors.WHITE) {\n p[w] = u;\n DFSVisit(w, color, d, f, p, time, adjList);\n }\n }\n color[u] = Colors.BLACK;\n f[u] = ++time.count;\n // console.log('explored ' + u);\n};\n\nexport const DFS = graph => {\n const vertices = graph.getVertices();\n const adjList = graph.getAdjList();\n const color = initializeColor(vertices);\n const d = {};\n const f = {};\n const p = {};\n const time = { count: 0 };\n for (let i = 0; i < vertices.length; i++) {\n f[vertices[i]] = 0;\n d[vertices[i]] = 0;\n p[vertices[i]] = null;\n }\n for (let i = 0; i < vertices.length; i++) {\n if (color[vertices[i]] === Colors.WHITE) {\n DFSVisit(vertices[i], color, d, f, p, time, adjList);\n }\n }\n return {\n discovery: d,\n finished: f,\n predecessors: p\n };\n};\n","import Queue from '../../data-structures/queue';\n\nconst Colors = {\n WHITE: 0,\n GREY: 1,\n BLACK: 2\n};\n\nconst initializeColor = vertices => {\n const color = {};\n for (let i = 0; i < vertices.length; i++) {\n color[vertices[i]] = Colors.WHITE;\n }\n return color;\n};\n\nexport const breadthFirstSearch = (graph, startVertex, callback) => {\n const vertices = graph.getVertices();\n const adjList = graph.getAdjList();\n const color = initializeColor(vertices);\n const queue = new Queue();\n\n queue.enqueue(startVertex);\n\n while (!queue.isEmpty()) {\n const u = queue.dequeue();\n const neighbors = adjList.get(u);\n color[u] = Colors.GREY;\n for (let i = 0; i < neighbors.length; i++) {\n const w = neighbors[i];\n if (color[w] === Colors.WHITE) {\n color[w] = Colors.GREY;\n queue.enqueue(w);\n }\n }\n color[u] = Colors.BLACK;\n if (callback) {\n callback(u);\n }\n }\n};\n\nexport const BFS = (graph, startVertex) => {\n const vertices = graph.getVertices();\n const adjList = graph.getAdjList();\n const color = initializeColor(vertices);\n const queue = new Queue();\n const distances = {};\n const predecessors = {};\n queue.enqueue(startVertex);\n for (let i = 0; i < vertices.length; i++) {\n distances[vertices[i]] = 0;\n predecessors[vertices[i]] = null;\n }\n while (!queue.isEmpty()) {\n const u = queue.dequeue();\n const neighbors = adjList.get(u);\n color[u] = Colors.GREY;\n for (let i = 0; i < neighbors.length; i++) {\n const w = neighbors[i];\n if (color[w] === Colors.WHITE) {\n color[w] = Colors.GREY;\n distances[w] = distances[u] + 1;\n predecessors[w] = u;\n queue.enqueue(w);\n }\n }\n color[u] = Colors.BLACK;\n }\n return {\n distances,\n predecessors\n };\n};\n","import Dictionary from './dictionary';\n\nexport default class Graph {\n constructor(isDirected = false) {\n this.isDirected = isDirected;\n this.vertices = [];\n this.adjList = new Dictionary();\n }\n addVertex(v) {\n if (!this.vertices.includes(v)) {\n this.vertices.push(v);\n this.adjList.set(v, []); // initialize adjacency list with array as well;\n }\n }\n addEdge(a, b) {\n if (!this.adjList.get(a)) {\n this.addVertex(a);\n }\n if (!this.adjList.get(b)) {\n this.addVertex(b);\n }\n this.adjList.get(a).push(b);\n if (this.isDirected !== true) {\n this.adjList.get(b).push(a);\n }\n }\n getVertices() {\n return this.vertices;\n }\n getAdjList() {\n return this.adjList;\n }\n toString() {\n let s = '';\n for (let i = 0; i < this.vertices.length; i++) {\n s += `${this.vertices[i]} -> `;\n const neighbors = this.adjList.get(this.vertices[i]);\n for (let j = 0; j < neighbors.length; j++) {\n s += `${neighbors[j]} `;\n }\n s += '\\n';\n }\n return s;\n }\n}\n","import { defaultCompare, swap } from '../../util';\n\nfunction heapify(array, index, heapSize, compareFn) {\n let largest = index;\n const left = (2 * index) + 1;\n const right = (2 * index) + 2;\n if (left < heapSize && compareFn(array[left], array[index]) > 0) {\n largest = left;\n }\n if (right < heapSize && compareFn(array[right], array[largest]) > 0) {\n largest = right;\n }\n if (largest !== index) {\n swap(array, index, largest);\n heapify(array, largest, heapSize, compareFn);\n }\n}\n\nfunction buildMaxHeap(array, compareFn) {\n for (let i = Math.floor(array.length / 2); i >= 0; i -= 1) {\n heapify(array, i, array.length, compareFn);\n }\n return array;\n}\n\nexport default function heapSort(array, compareFn = defaultCompare) {\n let heapSize = array.length;\n buildMaxHeap(array, compareFn);\n while (heapSize > 1) {\n swap(array, 0, --heapSize);\n heapify(array, 0, heapSize, compareFn);\n }\n return array;\n}\n","import { Compare, defaultCompare, reverseCompare, swap } from '../util';\n\nexport class MinHeap {\n constructor(compareFn = defaultCompare) {\n this.compareFn = compareFn;\n this.heap = [];\n }\n getLeftIndex(index) {\n return (2 * index) + 1;\n }\n getRightIndex(index) {\n return (2 * index) + 2;\n }\n getParentIndex(index) {\n if (index === 0) {\n return undefined;\n }\n return Math.floor((index - 1) / 2);\n }\n size() {\n return this.heap.length;\n }\n isEmpty() {\n return this.size() <= 0;\n }\n clear() {\n this.heap = [];\n }\n findMinimum() {\n return this.isEmpty() ? undefined : this.heap[0];\n }\n insert(value) {\n if (value != null) {\n const index = this.heap.length;\n this.heap.push(value);\n this.siftUp(index);\n return true;\n }\n return false;\n }\n siftDown(index) {\n let element = index;\n const left = this.getLeftIndex(index);\n const right = this.getRightIndex(index);\n const size = this.size();\n if (\n left < size &&\n this.compareFn(this.heap[element], this.heap[left]) === Compare.BIGGER_THAN\n ) {\n element = left;\n }\n if (\n right < size &&\n this.compareFn(this.heap[element], this.heap[right]) === Compare.BIGGER_THAN\n ) {\n element = right;\n }\n if (index !== element) {\n swap(this.heap, index, element);\n this.siftDown(element);\n }\n }\n siftUp(index) {\n let parent = this.getParentIndex(index);\n while (\n index > 0 &&\n this.compareFn(this.heap[parent], this.heap[index]) === Compare.BIGGER_THAN\n ) {\n swap(this.heap, parent, index);\n index = parent;\n parent = this.getParentIndex(index);\n }\n }\n extract() {\n if (this.isEmpty()) {\n return undefined;\n }\n if (this.size() === 1) {\n return this.heap.shift();\n }\n const removedValue = this.heap[0];\n this.heap[0] = this.heap.pop();\n this.siftDown(0);\n return removedValue;\n }\n heapify(array) {\n if (array) {\n this.heap = array;\n }\n const maxIndex = Math.floor(this.size() / 2) - 1;\n for (let i = 0; i <= maxIndex; i++) {\n this.siftDown(i);\n }\n return this.heap;\n }\n getAsArray() {\n return this.heap;\n }\n}\nexport class MaxHeap extends MinHeap {\n constructor(compareFn = defaultCompare) {\n super(compareFn);\n this.compareFn = compareFn;\n this.compareFn = reverseCompare(compareFn);\n }\n}\n","import { Compare, defaultCompare } from '../util';\nimport BinarySearchTree from './binary-search-tree';\nimport { Node } from './models/node';\n\nconst BalanceFactor = {\n UNBALANCED_RIGHT: 1,\n SLIGHTLY_UNBALANCED_RIGHT: 2,\n BALANCED: 3,\n SLIGHTLY_UNBALANCED_LEFT: 4,\n UNBALANCED_LEFT: 5\n};\n\nexport default class AVLTree extends BinarySearchTree {\n constructor(compareFn = defaultCompare) {\n super(compareFn);\n this.compareFn = compareFn;\n this.root = null;\n }\n getNodeHeight(node) {\n if (node == null) {\n return -1;\n }\n return Math.max(this.getNodeHeight(node.left), this.getNodeHeight(node.right)) + 1;\n }\n /**\n * Left left case: rotate right\n *\n * b a\n * / \\ / \\\n * a e -> rotationLL(b) -> c b\n * / \\ / \\\n * c d d e\n *\n * @param node Node\n */\n rotationLL(node) {\n const tmp = node.left;\n node.left = tmp.right;\n tmp.right = node;\n return tmp;\n }\n /**\n * Right right case: rotate left\n *\n * a b\n * / \\ / \\\n * c b -> rotationRR(a) -> a e\n * / \\ / \\\n * d e c d\n *\n * @param node Node\n */\n rotationRR(node) {\n const tmp = node.right;\n node.right = tmp.left;\n tmp.left = node;\n return tmp;\n }\n /**\n * Left right case: rotate left then right\n * @param node Node\n */\n rotationLR(node) {\n node.left = this.rotationRR(node.left);\n return this.rotationLL(node);\n }\n /**\n * Right left case: rotate right then left\n * @param node Node\n */\n rotationRL(node) {\n node.right = this.rotationLL(node.right);\n return this.rotationRR(node);\n }\n getBalanceFactor(node) {\n const heightDifference = this.getNodeHeight(node.left) - this.getNodeHeight(node.right);\n switch (heightDifference) {\n case -2:\n return BalanceFactor.UNBALANCED_RIGHT;\n case -1:\n return BalanceFactor.SLIGHTLY_UNBALANCED_RIGHT;\n case 1:\n return BalanceFactor.SLIGHTLY_UNBALANCED_LEFT;\n case 2:\n return BalanceFactor.UNBALANCED_LEFT;\n default:\n return BalanceFactor.BALANCED;\n }\n }\n insert(key) {\n this.root = this.insertNode(this.root, key);\n }\n insertNode(node, key) {\n if (node == null) {\n return new Node(key);\n } else if (this.compareFn(key, node.key) === Compare.LESS_THAN) {\n node.left = this.insertNode(node.left, key);\n } else if (this.compareFn(key, node.key) === Compare.BIGGER_THAN) {\n node.right = this.insertNode(node.right, key);\n } else {\n return node; // duplicated key\n }\n // verify if tree is balanced\n const balanceFactor = this.getBalanceFactor(node);\n if (balanceFactor === BalanceFactor.UNBALANCED_LEFT) {\n if (this.compareFn(key, node.left.key) === Compare.LESS_THAN) {\n // Left left case\n node = this.rotationLL(node);\n } else {\n // Left right case\n return this.rotationLR(node);\n }\n }\n if (balanceFactor === BalanceFactor.UNBALANCED_RIGHT) {\n if (this.compareFn(key, node.right.key) === Compare.BIGGER_THAN) {\n // Right right case\n node = this.rotationRR(node);\n } else {\n // Right left case\n return this.rotationRL(node);\n }\n }\n return node;\n }\n removeNode(node, key) {\n node = super.removeNode(node, key); // {1}\n if (node == null) {\n return node;\n }\n // verify if tree is balanced\n const balanceFactor = this.getBalanceFactor(node);\n if (balanceFactor === BalanceFactor.UNBALANCED_LEFT) {\n // Left left case\n if (\n this.getBalanceFactor(node.left) === BalanceFactor.BALANCED ||\n this.getBalanceFactor(node.left) === BalanceFactor.SLIGHTLY_UNBALANCED_LEFT\n ) {\n return this.rotationLL(node);\n }\n // Left right case\n if (this.getBalanceFactor(node.left) === BalanceFactor.SLIGHTLY_UNBALANCED_RIGHT) {\n return this.rotationLR(node.left);\n }\n }\n if (balanceFactor === BalanceFactor.UNBALANCED_RIGHT) {\n // Right right case\n if (\n this.getBalanceFactor(node.right) === BalanceFactor.BALANCED ||\n this.getBalanceFactor(node.right) === BalanceFactor.SLIGHTLY_UNBALANCED_RIGHT\n ) {\n return this.rotationRR(node);\n }\n // Right left case\n if (this.getBalanceFactor(node.right) === BalanceFactor.SLIGHTLY_UNBALANCED_LEFT) {\n return this.rotationRL(node.right);\n }\n }\n return node;\n }\n}\n","export function fibonacci(n) {\n if (n < 1) {\n return 0;\n }\n if (n <= 2) {\n return 1;\n }\n return fibonacci(n - 1) + fibonacci(n - 2);\n}\n\nexport function fibonacciIterative(n) {\n if (n < 1) { return 0; }\n let fibNMinus2 = 0;\n let fibNMinus1 = 1;\n let fibN = n;\n for (let i = 2; i <= n; i++) {\n fibN = fibNMinus1 + fibNMinus2;\n fibNMinus2 = fibNMinus1;\n fibNMinus1 = fibN;\n }\n return fibN;\n}\n\nexport function fibonacciMemoization(n) {\n if (n < 1) { return 0; }\n const memo = [0, 1];\n const fibonacciMem = num => {\n if (memo[num] != null) { return memo[num]; }\n return (memo[num] = fibonacciMem(num - 1) + fibonacciMem(num - 2));\n };\n return fibonacciMem(n);\n}\n","export function factorialIterative(number) {\n if (number < 0) {\n return undefined;\n }\n let total = 1;\n for (let n = number; n > 1; n--) {\n total *= n;\n }\n return total;\n}\n\nexport function factorial(n) {\n if (n < 0) {\n return undefined;\n }\n if (n === 1 || n === 0) {\n return 1;\n }\n return n * factorial(n - 1);\n}\n","import { ValuePair } from './value-pair';\n\nexport class ValuePairLazy extends ValuePair {\n constructor(key, value, isDeleted = false) {\n super(key, value);\n this.key = key;\n this.value = value;\n this.isDeleted = isDeleted;\n }\n}\n","import { defaultToString } from '../util';\nimport { ValuePairLazy } from './models/value-pair-lazy';\n\nexport default class HashTableLinearProbingLazy {\n constructor(toStrFn = defaultToString) {\n this.toStrFn = toStrFn;\n this.table = {};\n }\n loseloseHashCode(key) {\n if (typeof key === 'number') {\n return key;\n }\n const tableKey = this.toStrFn(key);\n let hash = 0;\n for (let i = 0; i < tableKey.length; i++) {\n hash += tableKey.charCodeAt(i);\n }\n return hash % 37;\n }\n hashCode(key) {\n return this.loseloseHashCode(key);\n }\n put(key, value) {\n if (key != null && value != null) {\n const position = this.hashCode(key);\n if (\n this.table[position] == null ||\n (this.table[position] != null && this.table[position].isDeleted)\n ) {\n this.table[position] = new ValuePairLazy(key, value);\n } else {\n let index = position + 1;\n while (this.table[index] != null && !this.table[position].isDeleted) {\n index++;\n }\n this.table[index] = new ValuePairLazy(key, value);\n }\n return true;\n }\n return false;\n }\n get(key) {\n const position = this.hashCode(key);\n if (this.table[position] != null) {\n if (this.table[position].key === key && !this.table[position].isDeleted) {\n return this.table[position].value;\n }\n let index = position + 1;\n while (\n this.table[index] != null &&\n (this.table[index].key !== key || this.table[index].isDeleted)\n ) {\n if (this.table[index].key === key && this.table[index].isDeleted) {\n return undefined;\n }\n index++;\n }\n if (\n this.table[index] != null &&\n this.table[index].key === key &&\n !this.table[index].isDeleted\n ) {\n return this.table[position].value;\n }\n }\n return undefined;\n }\n remove(key) {\n const position = this.hashCode(key);\n if (this.table[position] != null) {\n if (this.table[position].key === key && !this.table[position].isDeleted) {\n this.table[position].isDeleted = true;\n return true;\n }\n let index = position + 1;\n while (\n this.table[index] != null &&\n (this.table[index].key !== key || this.table[index].isDeleted)\n ) {\n index++;\n }\n if (\n this.table[index] != null &&\n this.table[index].key === key &&\n !this.table[index].isDeleted\n ) {\n this.table[index].isDeleted = true;\n return true;\n }\n }\n return false;\n }\n isEmpty() {\n return this.size() === 0;\n }\n size() {\n let count = 0;\n Object.values(this.table).forEach(valuePair => {\n count += valuePair.isDeleted === true ? 0 : 1;\n });\n return count;\n }\n clear() {\n this.table = {};\n }\n getTable() {\n return this.table;\n }\n toString() {\n if (this.isEmpty()) {\n return '';\n }\n const keys = Object.keys(this.table);\n let objString = `{${keys[0]} => ${this.table[keys[0]].toString()}}`;\n for (let i = 1; i < keys.length; i++) {\n objString = `${objString},{${keys[i]} => ${this.table[\n keys[i]\n ].toString()}}`;\n }\n return objString;\n }\n}\n","import { defaultToString } from '../util';\nimport { ValuePair } from './models/value-pair';\n\nexport default class HashTableLinearProbing {\n constructor(toStrFn = defaultToString) {\n this.toStrFn = toStrFn;\n this.table = {};\n }\n loseloseHashCode(key) {\n if (typeof key === 'number') {\n return key;\n }\n const tableKey = this.toStrFn(key);\n let hash = 0;\n for (let i = 0; i < tableKey.length; i++) {\n hash += tableKey.charCodeAt(i);\n }\n return hash % 37;\n }\n hashCode(key) {\n return this.loseloseHashCode(key);\n }\n put(key, value) {\n if (key != null && value != null) {\n const position = this.hashCode(key);\n if (this.table[position] == null) {\n this.table[position] = new ValuePair(key, value);\n } else {\n let index = position + 1;\n while (this.table[index] != null) {\n index++;\n }\n this.table[index] = new ValuePair(key, value);\n }\n return true;\n }\n return false;\n }\n get(key) {\n const position = this.hashCode(key);\n if (this.table[position] != null) {\n if (this.table[position].key === key) {\n return this.table[position].value;\n }\n let index = position + 1;\n while (this.table[index] != null && this.table[index].key !== key) {\n index++;\n }\n if (this.table[index] != null && this.table[index].key === key) {\n return this.table[position].value;\n }\n }\n return undefined;\n }\n remove(key) {\n const position = this.hashCode(key);\n if (this.table[position] != null) {\n if (this.table[position].key === key) {\n delete this.table[position];\n this.verifyRemoveSideEffect(key, position);\n return true;\n }\n let index = position + 1;\n while (this.table[index] != null && this.table[index].key !== key) {\n index++;\n }\n if (this.table[index] != null && this.table[index].key === key) {\n delete this.table[index];\n this.verifyRemoveSideEffect(key, index);\n return true;\n }\n }\n return false;\n }\n verifyRemoveSideEffect(key, removedPosition) {\n const hash = this.hashCode(key);\n let index = removedPosition + 1;\n while (this.table[index] != null) {\n const posHash = this.hashCode(this.table[index].key);\n if (posHash <= hash || posHash <= removedPosition) {\n this.table[removedPosition] = this.table[index];\n delete this.table[index];\n removedPosition = index;\n }\n index++;\n }\n }\n isEmpty() {\n return this.size() === 0;\n }\n size() {\n return Object.keys(this.table).length;\n }\n clear() {\n this.table = {};\n }\n getTable() {\n return this.table;\n }\n toString() {\n if (this.isEmpty()) {\n return '';\n }\n const keys = Object.keys(this.table);\n let objString = `{${keys[0]} => ${this.table[keys[0]].toString()}}`;\n for (let i = 1; i < keys.length; i++) {\n objString = `${objString},{${keys[i]} => ${this.table[\n keys[i]\n ].toString()}}`;\n }\n return objString;\n }\n}\n","import { defaultToString } from '../util';\nimport LinkedList from './linked-list';\nimport { ValuePair } from './models/value-pair';\n\nexport default class HashTableSeparateChaining {\n constructor(toStrFn = defaultToString) {\n this.toStrFn = toStrFn;\n this.table = {};\n }\n loseloseHashCode(key) {\n if (typeof key === 'number') {\n return key;\n }\n const tableKey = this.toStrFn(key);\n let hash = 0;\n for (let i = 0; i < tableKey.length; i++) {\n hash += tableKey.charCodeAt(i);\n }\n return hash % 37;\n }\n hashCode(key) {\n return this.loseloseHashCode(key);\n }\n put(key, value) {\n if (key != null && value != null) {\n const position = this.hashCode(key);\n if (this.table[position] == null) {\n this.table[position] = new LinkedList();\n }\n this.table[position].push(new ValuePair(key, value));\n return true;\n }\n return false;\n }\n get(key) {\n const position = this.hashCode(key);\n const linkedList = this.table[position];\n if (linkedList != null && !linkedList.isEmpty()) {\n let current = linkedList.getHead();\n while (current != null) {\n if (current.element.key === key) {\n return current.element.value;\n }\n current = current.next;\n }\n }\n return undefined;\n }\n remove(key) {\n const position = this.hashCode(key);\n const linkedList = this.table[position];\n if (linkedList != null && !linkedList.isEmpty()) {\n let current = linkedList.getHead();\n while (current != null) {\n if (current.element.key === key) {\n linkedList.remove(current.element);\n if (linkedList.isEmpty()) {\n delete this.table[position];\n }\n return true;\n }\n current = current.next;\n }\n }\n return false;\n }\n isEmpty() {\n return this.size() === 0;\n }\n size() {\n let count = 0;\n Object.values(this.table).forEach(linkedList => {\n count += linkedList.size();\n });\n return count;\n }\n clear() {\n this.table = {};\n }\n getTable() {\n return this.table;\n }\n toString() {\n if (this.isEmpty()) {\n return '';\n }\n const keys = Object.keys(this.table);\n let objString = `{${keys[0]} => ${this.table[keys[0]].toString()}}`;\n for (let i = 1; i < keys.length; i++) {\n objString = `${objString},{${keys[i]} => ${this.table[\n keys[i]\n ].toString()}}`;\n }\n return objString;\n }\n}\n","import { defaultToString } from '../util';\nimport { ValuePair } from './models/value-pair';\n\nexport default class HashTable {\n constructor(toStrFn = defaultToString) {\n this.toStrFn = toStrFn;\n this.table = {};\n }\n loseloseHashCode(key) {\n if (typeof key === 'number') {\n return key;\n }\n const tableKey = this.toStrFn(key);\n let hash = 0;\n for (let i = 0; i < tableKey.length; i++) {\n hash += tableKey.charCodeAt(i);\n }\n return hash % 37;\n }\n /* djb2HashCode(key) {\n const tableKey = this.toStrFn(key);\n let hash = 5381;\n for (let i = 0; i < tableKey.length; i++) {\n hash = (hash * 33) + tableKey.charCodeAt(i);\n }\n return hash % 1013;\n } */\n hashCode(key) {\n return this.loseloseHashCode(key);\n }\n put(key, value) {\n if (key != null && value != null) {\n const position = this.hashCode(key);\n this.table[position] = new ValuePair(key, value);\n return true;\n }\n return false;\n }\n get(key) {\n const valuePair = this.table[this.hashCode(key)];\n return valuePair == null ? undefined : valuePair.value;\n }\n remove(key) {\n const hash = this.hashCode(key);\n const valuePair = this.table[hash];\n if (valuePair != null) {\n delete this.table[hash];\n return true;\n }\n return false;\n }\n getTable() {\n return this.table;\n }\n isEmpty() {\n return this.size() === 0;\n }\n size() {\n return Object.keys(this.table).length;\n }\n clear() {\n this.table = {};\n }\n toString() {\n if (this.isEmpty()) {\n return '';\n }\n const keys = Object.keys(this.table);\n let objString = `{${keys[0]} => ${this.table[keys[0]].toString()}}`;\n for (let i = 1; i < keys.length; i++) {\n objString = `${objString},{${keys[i]} => ${this.table[keys[i]].toString()}}`;\n }\n return objString;\n }\n}\n","export default class Set {\n constructor() {\n this.items = {};\n }\n add(element) {\n if (!this.has(element)) {\n this.items[element] = element;\n return true;\n }\n return false;\n }\n delete(element) {\n if (this.has(element)) {\n delete this.items[element];\n return true;\n }\n return false;\n }\n has(element) {\n return Object.prototype.hasOwnProperty.call(this.items, element);\n }\n values() {\n return Object.values(this.items);\n }\n union(otherSet) {\n const unionSet = new Set();\n this.values().forEach(value => unionSet.add(value));\n otherSet.values().forEach(value => unionSet.add(value));\n return unionSet;\n }\n intersection(otherSet) {\n const intersectionSet = new Set();\n const values = this.values();\n const otherValues = otherSet.values();\n let biggerSet = values;\n let smallerSet = otherValues;\n if (otherValues.length - values.length > 0) {\n biggerSet = otherValues;\n smallerSet = values;\n }\n smallerSet.forEach(value => {\n if (biggerSet.includes(value)) {\n intersectionSet.add(value);\n }\n });\n return intersectionSet;\n }\n difference(otherSet) {\n const differenceSet = new Set();\n this.values().forEach(value => {\n if (!otherSet.has(value)) {\n differenceSet.add(value);\n }\n });\n return differenceSet;\n }\n isSubsetOf(otherSet) {\n if (this.size() > otherSet.size()) {\n return false;\n }\n let isSubset = true;\n this.values().every(value => {\n if (!otherSet.has(value)) {\n isSubset = false;\n return false;\n }\n return true;\n });\n return isSubset;\n }\n isEmpty() {\n return this.size() === 0;\n }\n size() {\n return Object.keys(this.items).length;\n }\n clear() {\n this.items = {};\n }\n toString() {\n if (this.isEmpty()) {\n return '';\n }\n const values = this.values();\n let objString = `${values[0]}`;\n for (let i = 1; i < values.length; i++) {\n objString = `${objString},${values[i].toString()}`;\n }\n return objString;\n }\n}\n","import DoublyLinkedList from './doubly-linked-list';\n\nexport default class StackLinkedList {\n constructor() {\n this.items = new DoublyLinkedList();\n }\n push(element) {\n this.items.push(element);\n }\n pop() {\n if (this.isEmpty()) {\n return undefined;\n }\n const result = this.items.removeAt(this.size() - 1);\n return result;\n }\n peek() {\n if (this.isEmpty()) {\n return undefined;\n }\n return this.items.getElementAt(this.size() - 1).element;\n }\n isEmpty() {\n return this.items.isEmpty();\n }\n size() {\n return this.items.size();\n }\n clear() {\n this.items.clear();\n }\n toString() {\n return this.items.toString();\n }\n}\n","import { Compare, defaultCompare, defaultEquals } from '../util';\nimport LinkedList from './linked-list';\n\nexport default class SortedLinkedList extends LinkedList {\n constructor(equalsFn = defaultEquals, compareFn = defaultCompare) {\n super(equalsFn);\n this.equalsFn = equalsFn;\n this.compareFn = compareFn;\n }\n push(element) {\n if (this.isEmpty()) {\n super.push(element);\n } else {\n const index = this.getIndexNextSortedElement(element);\n super.insert(element, index);\n }\n }\n insert(element, index = 0) {\n if (this.isEmpty()) {\n return super.insert(element, index === 0 ? index : 0);\n }\n const pos = this.getIndexNextSortedElement(element);\n return super.insert(element, pos);\n }\n getIndexNextSortedElement(element) {\n let current = this.head;\n let i = 0;\n for (; i < this.size() && current; i++) {\n const comp = this.compareFn(element, current.element);\n if (comp === Compare.LESS_THAN) {\n return i;\n }\n current = current.next;\n }\n return i;\n }\n}\n","import { defaultEquals } from '../util';\nimport LinkedList from './linked-list';\nimport { Node } from './models/linked-list-models';\n\nexport default class CircularLinkedList extends LinkedList {\n constructor(equalsFn = defaultEquals) {\n super(equalsFn);\n }\n push(element) {\n const node = new Node(element);\n let current;\n if (this.head == null) {\n this.head = node;\n } else {\n current = this.getElementAt(this.size() - 1);\n current.next = node;\n }\n // set node.next to head - to have circular list\n node.next = this.head;\n this.count++;\n }\n insert(element, index) {\n if (index >= 0 && index <= this.count) {\n const node = new Node(element);\n let current = this.head;\n if (index === 0) {\n if (this.head == null) {\n // if no node in list\n this.head = node;\n node.next = this.head;\n } else {\n node.next = current;\n current = this.getElementAt(this.size());\n // update last element\n this.head = node;\n current.next = this.head;\n }\n } else {\n const previous = this.getElementAt(index - 1);\n node.next = previous.next;\n previous.next = node;\n }\n this.count++;\n return true;\n }\n return false;\n }\n removeAt(index) {\n if (index >= 0 && index < this.count) {\n let current = this.head;\n if (index === 0) {\n if (this.size() === 1) {\n this.head = undefined;\n } else {\n const removed = this.head;\n current = this.getElementAt(this.size() - 1);\n this.head = this.head.next;\n current.next = this.head;\n current = removed;\n }\n } else {\n // no need to update last element for circular list\n const previous = this.getElementAt(index - 1);\n current = previous.next;\n previous.next = current.next;\n }\n this.count--;\n return current.element;\n }\n return undefined;\n }\n}\n","import Deque from '../data-structures/deque';\n\nexport function palindromeChecker(aString) {\n if (\n aString === undefined ||\n aString === null ||\n (aString !== null && aString.length === 0)\n ) {\n return false;\n }\n const deque = new Deque();\n const lowerString = aString.toLocaleLowerCase().split(' ').join('');\n let firstChar;\n let lastChar;\n\n for (let i = 0; i < lowerString.length; i++) {\n deque.addBack(lowerString.charAt(i));\n }\n\n while (deque.size() > 1) {\n firstChar = deque.removeFront();\n lastChar = deque.removeBack();\n if (firstChar !== lastChar) {\n return false;\n }\n }\n\n return true;\n}\n","import Queue from '../data-structures/queue';\n\nexport function hotPotato(elementsList, num) {\n const queue = new Queue();\n const elimitatedList = [];\n\n for (let i = 0; i < elementsList.length; i++) {\n queue.enqueue(elementsList[i]);\n }\n\n while (queue.size() > 1) {\n for (let i = 0; i < num; i++) {\n queue.enqueue(queue.dequeue());\n }\n elimitatedList.push(queue.dequeue());\n }\n\n return {\n eliminated: elimitatedList,\n winner: queue.dequeue()\n };\n}\n","// @ts-check\nimport Stack from '../data-structures/stack';\n\nexport function parenthesesChecker(symbols) {\n const stack = new Stack();\n const opens = '([{';\n const closers = ')]}';\n let balanced = true;\n let index = 0;\n let symbol;\n let top;\n\n while (index < symbols.length && balanced) {\n symbol = symbols[index];\n if (opens.indexOf(symbol) >= 0) {\n stack.push(symbol);\n } else if (stack.isEmpty()) {\n balanced = false;\n } else {\n top = stack.pop();\n if (!(opens.indexOf(top) === closers.indexOf(symbol))) {\n balanced = false;\n }\n }\n index++;\n }\n return balanced && stack.isEmpty();\n}\n","// @ts-check\nimport Stack from '../data-structures/stack';\n\nexport function decimalToBinary(decNumber) {\n const remStack = new Stack();\n let number = decNumber;\n let rem;\n let binaryString = '';\n\n while (number > 0) {\n rem = Math.floor(number % 2);\n remStack.push(rem);\n number = Math.floor(number / 2);\n }\n\n while (!remStack.isEmpty()) {\n binaryString += remStack.pop().toString();\n }\n\n return binaryString;\n}\n\nexport function baseConverter(decNumber, base) {\n const remStack = new Stack();\n const digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';\n let number = decNumber;\n let rem;\n let baseString = '';\n\n if (!(base >= 2 && base <= 36)) {\n return '';\n }\n\n while (number > 0) {\n rem = Math.floor(number % base);\n remStack.push(rem);\n number = Math.floor(number / base);\n }\n\n while (!remStack.isEmpty()) {\n baseString += digits[remStack.pop()];\n }\n\n return baseString;\n}\n","// @ts-check\nimport Stack from '../data-structures/stack';\n\nfunction towerOfHanoi(plates, source, helper, dest, sourceName, helperName, destName, moves = []) {\n if (plates <= 0) {\n return moves;\n }\n if (plates === 1) {\n dest.push(source.pop());\n const move = {};\n move[sourceName] = source.toString();\n move[helperName] = helper.toString();\n move[destName] = dest.toString();\n moves.push(move);\n } else {\n towerOfHanoi(plates - 1, source, dest, helper, sourceName, destName, helperName, moves);\n dest.push(source.pop());\n const move = {};\n move[sourceName] = source.toString();\n move[helperName] = helper.toString();\n move[destName] = dest.toString();\n moves.push(move);\n towerOfHanoi(plates - 1, helper, source, dest, helperName, sourceName, destName, moves);\n }\n return moves;\n}\n\nexport function hanoiStack(plates) {\n const source = new Stack();\n const dest = new Stack();\n const helper = new Stack();\n\n for (let i = plates; i > 0; i--) {\n source.push(i);\n }\n\n return towerOfHanoi(plates, source, helper, dest, 'source', 'helper', 'dest');\n}\n\nexport function hanoi(plates, source, helper, dest, moves = []) {\n if (plates <= 0) {\n return moves;\n }\n if (plates === 1) {\n moves.push([source, dest]);\n } else {\n hanoi(plates - 1, source, dest, helper, moves);\n moves.push([source, dest]);\n hanoi(plates - 1, helper, source, dest, moves);\n }\n return moves;\n}\n","// @ts-check\n\nexport default class StackArray {\n constructor() {\n this.items = [];\n }\n push(element) {\n this.items.push(element);\n }\n\n pop() {\n return this.items.pop();\n }\n\n peek() {\n return this.items[this.items.length - 1];\n }\n\n isEmpty() {\n return this.items.length === 0;\n }\n\n size() {\n return this.items.length;\n }\n\n clear() {\n this.items = [];\n }\n\n toArray() {\n return this.items;\n }\n\n toString() {\n return this.items.toString();\n }\n}\n","import * as _util from './util';\n\n// chapters 05 and 07\nexport const util = _util;\n\n// chapter 03\nexport { default as StackArray } from './data-structures/stack-array';\nexport { default as Stack } from './data-structures/stack';\nexport { hanoi } from './others/hanoi';\nexport { hanoiStack } from './others/hanoi';\nexport { baseConverter } from './others/base-converter';\nexport { decimalToBinary } from './others/base-converter';\nexport { parenthesesChecker } from './others/balanced-symbols';\n\n// chapter 04\nexport { default as Queue } from './data-structures/queue';\nexport { default as Deque } from './data-structures/deque';\nexport { hotPotato } from './others/hot-potato';\nexport { palindromeChecker } from './others/palindrome-checker';\n\n// chapter 05\nexport { default as LinkedList } from './data-structures/linked-list';\nexport { default as DoublyLinkedList } from './data-structures/doubly-linked-list';\nexport { default as CircularLinkedList } from './data-structures/circular-linked-list';\nexport { default as SortedLinkedList } from './data-structures/sorted-linked-list';\nexport { default as StackLinkedList } from './data-structures/stack-linked-list';\n\n// chapter 06\nexport { default as Set } from './data-structures/set';\n\n// chapter 07\nexport { default as Dictionary } from './data-structures/dictionary';\nexport { default as HashTable } from './data-structures/hash-table';\nexport { default as HashTableSeparateChaining } from './data-structures/hash-table-separate-chaining';\nexport { default as HashTableLinearProbing } from './data-structures/hash-table-linear-probing';\nexport { default as HashTableLinearProbingLazy } from './data-structures/hash-table-linear-probing-lazy';\n\n// chapter 08\nexport { default as factorialIterative } from './others/factorial';\nexport { default as factorial } from './others/factorial';\nexport { default as fibonacci } from './others/fibonacci';\nexport { default as fibonacciIterative } from './others/fibonacci';\nexport { default as fibonacciMemoization } from './others/fibonacci';\n\n// chapter 09\nexport { default as BinarySearchTree } from './data-structures/binary-search-tree';\nexport { default as AVLTree } from './data-structures/avl-tree';\n\n// chapter 10\nexport { MinHeap } from './data-structures/heap';\nexport { MaxHeap } from './data-structures/heap';\nexport { default as heapSort } from './algorithms/sorting/heap-sort';\n\n// chapter 11\nexport { default as Graph } from './data-structures/graph';\nexport { breadthFirstSearch } from './algorithms/graph/breadth-first-search';\nexport { BFS } from './algorithms/graph/breadth-first-search';\nexport { depthFirstSearch } from './algorithms/graph/depth-first-search';\nexport { DFS } from './algorithms/graph/depth-first-search';\nexport { dijkstra } from './algorithms/graph/dijkstra';\nexport { floydWarshall } from './algorithms/graph/floyd-warshall';\nexport { prim } from './algorithms/graph/prim';\nexport { kruskal } from './algorithms/graph/kruskal';\n\n// chapter 12\nexport { shuffle } from './algorithms/shuffle/fisher–yates';\n\nexport { bubbleSort } from './algorithms/sorting/bubble-sort';\nexport { modifiedBubbleSort } from './algorithms/sorting/bubble-sort-improved';\nexport { bucketSort } from './algorithms/sorting/bucket-sort';\nexport { countingSort } from './algorithms/sorting/counting-sort';\nexport { insertionSort } from './algorithms/sorting/insertion-sort';\nexport { mergeSort } from './algorithms/sorting/merge-sort';\nexport { quickSort } from './algorithms/sorting/quicksort';\nexport { radixSort } from './algorithms/sorting/radix-sort';\nexport { selectionSort } from './algorithms/sorting/selection-sort';\nexport { shellSort } from './algorithms/sorting/shell-sort';\n\nexport { binarySearch } from './algorithms/search/binary-search';\nexport { interpolationSearch } from './algorithms/search/interpolation-search';\nexport { sequentialSearch } from './algorithms/search/sequential-search';\nexport { findMaxValue } from './algorithms/search/min-max-search';\nexport { findMinValue } from './algorithms/search/min-max-search';\n\n// chapter 14\nexport { binarySearch as binarySearchRecursive } from './algorithms/search/binary-search-recursive';\nexport { minCoinChange } from './algorithms/dynamic-programing/min-coin-change';\nexport { minCoinChange as minCoinChangeGreedy } from './algorithms/greedy/min-coin-change';\nexport { knapSack } from './algorithms/dynamic-programing/knapsack';\nexport { knapSack as knapSackRecursive } from './algorithms/dynamic-programing/knapsack-recursive';\nexport { knapSack as knapSackGreedy } from './algorithms/greedy/knapsack';\nexport { lcs } from './algorithms/dynamic-programing/longest-common-subsequence';\nexport { lcs as lcsPrint } from './algorithms/dynamic-programing/longest-common-subsequence-print';\nexport { lcs as lcsRecursive } from './algorithms/greedy/longest-common-subsequence';\nexport { matrixChainOrder } from './algorithms/dynamic-programing/matrix-chain-multiplication';\nexport { matrixChainOrder as matrixChainOrderGreedy } from './algorithms/greedy/matrix-chain-multiplication';\nexport { ratInAMaze } from './algorithms/backtracking/rat-in-maze';\nexport { sudokuSolver } from './algorithms/backtracking/sudoku-solver';\n"],"sourceRoot":""}
\ No newline at end of file
diff --git a/chapter01/01-HelloWorld.html b/examples/chapter01_02/01-HelloWorld.html
similarity index 100%
rename from chapter01/01-HelloWorld.html
rename to examples/chapter01_02/01-HelloWorld.html
diff --git a/examples/chapter01_02/01-HelloWorld.js b/examples/chapter01_02/01-HelloWorld.js
new file mode 100644
index 00000000..b67b0e2c
--- /dev/null
+++ b/examples/chapter01_02/01-HelloWorld.js
@@ -0,0 +1,10 @@
+// @ts-check
+/* eslint-disable */
+
+function output(t) {
+ document.write('' + t + '
');
+}
+
+alert('Hello, World!');
+console.log('Hello, World!');
+output('Hello, World!');
diff --git a/chapter01/02-Variables.html b/examples/chapter01_02/02-Variables.html
similarity index 100%
rename from chapter01/02-Variables.html
rename to examples/chapter01_02/02-Variables.html
diff --git a/examples/chapter01_02/02-Variables.js b/examples/chapter01_02/02-Variables.js
new file mode 100644
index 00000000..4d1cf7d5
--- /dev/null
+++ b/examples/chapter01_02/02-Variables.js
@@ -0,0 +1,40 @@
+// @ts-check
+/* eslint-disable */
+
+var num = 1; // {1}
+num = 3; // {2}
+
+var price = 1.5; // {3}
+var myName = 'Packt'; // {4}
+var trueValue = true; // {5}
+var nullVar = null; // {6}
+var und; // {7}
+
+console.log('num: ' + num);
+console.log('myName: ' + myName);
+console.log('trueValue: ' + trueValue);
+console.log('price: ' + price);
+console.log('nullVar: ' + nullVar);
+console.log('und: ' + und);
+
+// ******* Variable Scope
+
+var myVariable = 'global';
+myOtherVariable = 'global';
+
+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}
diff --git a/chapter01/03-Operators.html b/examples/chapter01_02/03-Operators.html
similarity index 100%
rename from chapter01/03-Operators.html
rename to examples/chapter01_02/03-Operators.html
diff --git a/chapter01/03-Operators.js b/examples/chapter01_02/03-Operators.js
similarity index 58%
rename from chapter01/03-Operators.js
rename to examples/chapter01_02/03-Operators.js
index d1044b92..7895b17b 100755
--- a/chapter01/03-Operators.js
+++ b/examples/chapter01_02/03-Operators.js
@@ -1,28 +1,25 @@
-/* Arithmetic operators */
-var num = 0;
+// @ts-check
+/* eslint-disable */
+/* Arithmetic operators */
+var num = 0; // {1}
console.log('num value is ' + num);
num = num + 2;
-
console.log('New num value is ' + num);
num = num * 3;
-
console.log('New num value is ' + num);
num = num / 2;
-
console.log('New num value is ' + num);
num++;
-
num--;
console.log('New num value is ' + num);
-console.log('num mod 2 value is ' + (num % 2));
-
+console.log('num mod 2 value is ' + num % 2);
/* Assignment operators */
num += 1;
@@ -45,24 +42,24 @@ console.log('num <= 1 : ' + (num <= 1));
/* Logical operators */
console.log('true && false : ' + (true && false));
console.log('true || false : ' + (true || false));
-console.log('!true : ' + (!true));
+console.log('!true : ' + !true);
/* Bitwise operators */
-console.log('5 & 1:', (5 & 1)); //same as 0101 & 0001 (result 0001 / 1)
-console.log('5 | 1:', (5 | 1)); //same as 0101 | 0001 (result 0101 / 5)
-console.log('~ 5:', (~5)); //same as ~0101 (result 1010 / 10)
-console.log('5 ^ 1:', (5 ^ 1)); //same as 0101 ^ 0001 (result 0100 / 4)
-console.log('5 << 1:', (5 << 1)); //same as 0101 << 1 (result 1010 / 10)
-console.log('5 >> 1:', (5 >> 1)); //same as 0101 >> 1 (result 0010 / 2)
+console.log('5 & 1:', 5 & 1); // same as 0101 & 0001 (result 0001 / 1)
+console.log('5 | 1:', 5 | 1); // same as 0101 | 0001 (result 0101 / 5)
+console.log('~ 5:', ~5); // same as ~0101 (result 1010 / 10)
+console.log('5 ^ 1:', 5 ^ 1); // same as 0101 ^ 0001 (result 0100 / 4)
+console.log('5 << 1:', 5 << 1); // same as 0101 << 1 (result 1010 / 10)
+console.log('5 >> 1:', 5 >> 1); // same as 0101 >> 1 (result 0010 / 2)
/* typeOf */
console.log('typeof num:', typeof num);
console.log('typeof Packt:', typeof 'Packt');
console.log('typeof true:', typeof true);
-console.log('typeof [1,2,3]:', typeof [1,2,3]);
-console.log('typeof {name:John}:', typeof {name:'John'});
+console.log('typeof [1,2,3]:', typeof [1, 2, 3]);
+console.log('typeof {name:John}:', typeof { name: 'John' });
/* delete */
-var myObj = {name: 'John', age: 21};
+var myObj = { name: 'John', age: 21 };
delete myObj.age;
-console.log(myObj); //Object {name: "John"}
\ No newline at end of file
+console.log(myObj); // Object {name: "John"}
diff --git a/chapter01/04-TruthyFalsy.html b/examples/chapter01_02/04-TruthyFalsy.html
similarity index 100%
rename from chapter01/04-TruthyFalsy.html
rename to examples/chapter01_02/04-TruthyFalsy.html
diff --git a/examples/chapter01_02/04-TruthyFalsy.js b/examples/chapter01_02/04-TruthyFalsy.js
new file mode 100644
index 00000000..c64fa3e1
--- /dev/null
+++ b/examples/chapter01_02/04-TruthyFalsy.js
@@ -0,0 +1,27 @@
+// @ts-check
+/* eslint-disable */
+
+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('a'); // true
+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)
+
+testTruthy({}); // true (object is always true)
+
+var obj = { name: 'John' };
+testTruthy(obj); // true
+testTruthy(obj.name); // true
+testTruthy(obj.age); // age (property does not exist)
diff --git a/chapter01/05-EqualsOperators.html b/examples/chapter01_02/05-EqualsOperators.html
similarity index 100%
rename from chapter01/05-EqualsOperators.html
rename to examples/chapter01_02/05-EqualsOperators.html
diff --git a/examples/chapter01_02/05-EqualsOperators.js b/examples/chapter01_02/05-EqualsOperators.js
new file mode 100644
index 00000000..d5b43ecc
--- /dev/null
+++ b/examples/chapter01_02/05-EqualsOperators.js
@@ -0,0 +1,39 @@
+// @ts-check
+/* eslint-disable */
+
+// Packt == true
+
+console.log('packt' ? true : false);
+// outputs true
+
+console.log('packt' == true);
+// 1 - converts Boolean using toNumber
+// 'packt' == 1
+// 2 - converts String using toNumber
+// NaN == 1
+// outputs false
+
+console.log('packt' == false);
+// 1 - converts Boolean using toNumber
+// 'packt' == 0
+// 2 - converts String using toNumber
+// NaN == 0
+// outputs false
+
+console.log([0] == true);
+// 1 - converts Boolean using toNumber
+// [0] == 1
+// 2 - converts Object using toPrimitive
+// 2.1 - [0].valueOf() is not primitive
+// 2.2 - [0].toString is 0
+// 0 == 1
+// outputs false
+
+//* ****************************** ===
+console.log('packt' === true); // false
+
+console.log('packt' === 'packt'); // true
+
+var person1 = { name: 'John' };
+var person2 = { name: 'John' };
+console.log(person1 === person2); // false, different objects
diff --git a/chapter01/06-ConditionalStatements.html b/examples/chapter01_02/06-ConditionalStatements.html
similarity index 100%
rename from chapter01/06-ConditionalStatements.html
rename to examples/chapter01_02/06-ConditionalStatements.html
diff --git a/examples/chapter01_02/06-ConditionalStatements.js b/examples/chapter01_02/06-ConditionalStatements.js
new file mode 100644
index 00000000..c939967c
--- /dev/null
+++ b/examples/chapter01_02/06-ConditionalStatements.js
@@ -0,0 +1,54 @@
+// @ts-check
+/* eslint-disable */
+
+/* Example 01 - if */
+var num = 1;
+if (num === 1) {
+ console.log('num is equal to 1');
+}
+
+/* Example 02 - if-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);
+}
+
+/* Example 03 - 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');
+}
+
+/* Example 04 - 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');
+}
+
+/* Example 05 - ternary operator - if..else */
+if (num === 1) {
+ num--;
+} else {
+ num++;
+}
+
+// is the same as
+num === 1 ? num-- : num++;
diff --git a/chapter01/07-Loops.html b/examples/chapter01_02/07-Loops.html
similarity index 100%
rename from chapter01/07-Loops.html
rename to examples/chapter01_02/07-Loops.html
diff --git a/chapter01/07-Loops.js b/examples/chapter01_02/07-Loops.js
similarity index 56%
rename from chapter01/07-Loops.js
rename to examples/chapter01_02/07-Loops.js
index 61cf20cb..9d12b19e 100755
--- a/chapter01/07-Loops.js
+++ b/examples/chapter01_02/07-Loops.js
@@ -1,23 +1,24 @@
-console.log('**** for example ****');
+// @ts-check
+/* eslint-disable */
+console.log('**** for example ****');
/* for - example */
-for (var i=0; i<10; i++) {
- console.log(i);
+for (var i = 0; i < 10; i++) {
+ console.log(i);
}
console.log('**** while example ****');
/* while - example */
var i = 0;
-while(i<10)
-{
- console.log(i);
- i++;
+while (i < 10) {
+ console.log(i);
+ i++;
}
console.log('**** do-while example ****');
/* do-while - example */
var i = 0;
do {
- console.log(i);
- i++;
-} while (i<10)
\ No newline at end of file
+ console.log(i);
+ i++;
+} while (i < 10);
diff --git a/chapter01/08-Functions.html b/examples/chapter01_02/08-Functions.html
similarity index 100%
rename from chapter01/08-Functions.html
rename to examples/chapter01_02/08-Functions.html
diff --git a/chapter01/08-Functions.js b/examples/chapter01_02/08-Functions.js
similarity index 66%
rename from chapter01/08-Functions.js
rename to examples/chapter01_02/08-Functions.js
index 9915e566..52d5f9c8 100644
--- a/chapter01/08-Functions.js
+++ b/examples/chapter01_02/08-Functions.js
@@ -1,12 +1,15 @@
+// @ts-check
+/* eslint-disable */
+
function sayHello() {
- console.log('Hello!');
+ console.log('Hello!');
}
sayHello();
/* function with parameter */
function output(text) {
- console.log(text);
+ console.log(text);
}
output('Hello!');
@@ -17,13 +20,8 @@ output();
/* function using the return statement */
function sum(num1, num2) {
- return num1 + num2;
+ return num1 + num2;
}
-var result = sum(1,2);
+var result = sum(1, 2);
output(result);
-
-
-
-
-
diff --git a/chapter01/10-ObjectOrientedJS.html b/examples/chapter01_02/09-ObjectOrientedJS.html
similarity index 59%
rename from chapter01/10-ObjectOrientedJS.html
rename to examples/chapter01_02/09-ObjectOrientedJS.html
index 1b3848bd..cfbe1a04 100644
--- a/chapter01/10-ObjectOrientedJS.html
+++ b/examples/chapter01_02/09-ObjectOrientedJS.html
@@ -5,6 +5,6 @@
-
+
-