├── cap03
└── arrays
│ ├── reverse.js
│ ├── from.js
│ ├── of.js
│ ├── keys.js
│ ├── every.js
│ ├── join.js
│ ├── for-of.js
│ ├── copy-within.js
│ ├── map.js
│ ├── reduce.js
│ ├── some.js
│ ├── filter.js
│ ├── remove-element-first-position.js
│ ├── includes.js
│ ├── add-elements.js
│ ├── fill.js
│ ├── concat.js
│ ├── fibonnaci.js
│ ├── entries.js
│ ├── initial-arrays.js
│ ├── arrays.js
│ ├── @@iterator.js
│ ├── insert-array-first-position.js
│ ├── re-index.js
│ ├── remove-first-position.js
│ ├── pesquisa.js
│ ├── array-two-dimensional-and-multidimensional.js
│ ├── sort.js
│ └── README.md
├── imgs
└── book-structure-javascript.png
├── cap02
├── introduction-typescript
│ ├── hello-world.ts
│ ├── type-inference.ts
│ ├── generics.ts
│ └── interfaces.ts
├── operator-exponencial.js
├── import.js
├── template-literals.js
├── modules.js
├── arrow-functions.js
├── rest-operators.js
├── values-default-parameters-func.js
├── property-of-objets.js
├── let-const.js
└── poo-with-class.js
├── README.md
└── cap01
├── loops.js
├── variables.js
├── functions.js
├── scope-variables.js
├── poo.js
├── true-and-false.js
├── instructions-conditions.js
├── functions-operators-equals.js
└── operators.js
/cap03/arrays/reverse.js:
--------------------------------------------------------------------------------
1 | const numbers = [1, 2, 3, 4, 5];
2 |
3 | console.log(numbers.reverse());
4 |
--------------------------------------------------------------------------------
/imgs/book-structure-javascript.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/williamkoller/structure-data-algorithms-javascript/HEAD/imgs/book-structure-javascript.png
--------------------------------------------------------------------------------
/cap03/arrays/from.js:
--------------------------------------------------------------------------------
1 | const numbers = [1, 2, 3, 4, 5];
2 |
3 | const number1 = Array.from(numbers, (value) => value % 2 === 0);
4 |
5 | console.log(number1);
6 |
--------------------------------------------------------------------------------
/cap03/arrays/of.js:
--------------------------------------------------------------------------------
1 | const number = Array.of(1);
2 |
3 | console.log(number);
4 |
5 | const numbers = Array.of(1, 2, 3, 4, 5);
6 |
7 | console.log(numbers);
8 |
--------------------------------------------------------------------------------
/cap03/arrays/keys.js:
--------------------------------------------------------------------------------
1 | const numbers1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
2 |
3 | const aKeys = numbers1.keys();
4 |
5 | console.log(aKeys.next());
6 |
--------------------------------------------------------------------------------
/cap02/introduction-typescript/hello-world.ts:
--------------------------------------------------------------------------------
1 | let myName2 = 'John';
2 | // myName = 10; // Error: Type '10' is not assignable to type 'string'.
3 |
4 | console.log(myName2);
5 |
--------------------------------------------------------------------------------
/cap03/arrays/every.js:
--------------------------------------------------------------------------------
1 | const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
2 | const isEven = (x) => x % 2 === 0;
3 |
4 | console.log(numbers.every(isEven));
5 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Book - Structure of Data Algorithms in JavaScript
2 |
3 |
4 |
--------------------------------------------------------------------------------
/cap03/arrays/join.js:
--------------------------------------------------------------------------------
1 | let numbers = [1, 2, 3, 4, 5];
2 |
3 | console.log(numbers.toString());
4 |
5 | const numbersString = numbers.join('-');
6 |
7 | console.log(numbersString);
8 |
--------------------------------------------------------------------------------
/cap03/arrays/for-of.js:
--------------------------------------------------------------------------------
1 | let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
2 |
3 | for (const number of numbers) {
4 | console.log(number % 2 === 0 ? 'even' : 'odd');
5 | }
6 |
--------------------------------------------------------------------------------
/cap03/arrays/copy-within.js:
--------------------------------------------------------------------------------
1 | let copyArray = [1, 2, 3, 4, 5, 6];
2 |
3 | console.log(copyArray.copyWithin(0, 3));
4 |
5 | copyArray = [1, 2, 3, 4, 5, 6];
6 |
7 | console.log(copyArray.copyWithin(1, 3, 5));
8 |
--------------------------------------------------------------------------------
/cap03/arrays/map.js:
--------------------------------------------------------------------------------
1 | const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
2 |
3 | const isEven = (x) => x % 2 === 0;
4 |
5 | const mapEven = numbers.map(isEven);
6 |
7 | console.log(mapEven);
8 |
--------------------------------------------------------------------------------
/cap03/arrays/reduce.js:
--------------------------------------------------------------------------------
1 | let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
2 |
3 | const isEven = (x) => x % 2 === 0;
4 |
5 | console.log(numbers.reduce((previous, current) => previous + current));
6 |
--------------------------------------------------------------------------------
/cap03/arrays/some.js:
--------------------------------------------------------------------------------
1 | let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
2 |
3 | const isEven = (x) => x % 2 === 0;
4 |
5 | let someEven = numbers.some(isEven);
6 |
7 | console.log(someEven);
8 |
9 |
--------------------------------------------------------------------------------
/cap03/arrays/filter.js:
--------------------------------------------------------------------------------
1 | let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
2 |
3 | const isEven = (x) => x % 2 === 0;
4 |
5 | let filterEven = numbers.filter(isEven);
6 |
7 | console.log(filterEven);
8 |
--------------------------------------------------------------------------------
/cap02/operator-exponencial.js:
--------------------------------------------------------------------------------
1 | const area = (r) => 3.14 * r * r;
2 | const area2 = (r) => 3.14 * Math.pow(r, 2);
3 | const area3 = (r) => 3.14 * r ** 2;
4 |
5 | console.log(area(3));
6 | console.log(area2(3));
7 | console.log(area3(3));
8 |
--------------------------------------------------------------------------------
/cap03/arrays/remove-element-first-position.js:
--------------------------------------------------------------------------------
1 | const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
2 |
3 | for (let i = 0; i < numbers.length; i++) {
4 | numbers[i] = numbers[i + 1];
5 | }
6 |
7 | console.log(numbers.length);
8 | console.log(numbers);
--------------------------------------------------------------------------------
/cap02/import.js:
--------------------------------------------------------------------------------
1 | import { circleArea as circle, squareArea as square, Book } from './modules.js';
2 |
3 | console.log(circle(2));
4 | console.log(square(2));
5 |
6 | const book = new Book('Learning JS DataStructures and Algorithms');
7 | book.printTitle();
8 |
--------------------------------------------------------------------------------
/cap02/introduction-typescript/type-inference.ts:
--------------------------------------------------------------------------------
1 | let age: number = 20
2 | let existsFlag: boolean = true
3 | let language: string = 'JavaScript'
4 |
5 | let favoriteLanguage: string
6 | let langs: string[] = ['JavaScript', 'Ruby', 'Python']
7 | favoriteLanguage = langs[0]
--------------------------------------------------------------------------------
/cap03/arrays/includes.js:
--------------------------------------------------------------------------------
1 | let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
2 |
3 | console.log(numbers.includes(17));
4 | console.log(numbers.includes(10));
5 |
6 | let numbers2 = [7, 6, 5, 4, 3, 2, 1];
7 |
8 | console.log(numbers2.includes(4, 5));
9 |
--------------------------------------------------------------------------------
/cap03/arrays/add-elements.js:
--------------------------------------------------------------------------------
1 | const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
2 |
3 | numbers[numbers.length] = 10
4 |
5 | console.log(numbers.length)
6 | console.log(numbers)
7 |
8 | numbers.push(11)
9 | numbers.push(12, 13)
10 |
11 | console.log(numbers.length)
12 | console.log(numbers)
--------------------------------------------------------------------------------
/cap03/arrays/fill.js:
--------------------------------------------------------------------------------
1 | const numbers = [1, 2, 3, 4, 5];
2 |
3 | const numbersCopy = Array.of(1, 2, 3, 4, 5);
4 |
5 | console.log(numbers.fill(0));
6 | console.log(numbers.fill(2, 1));
7 | console.log(numbers.fill(1, 3, 5));
8 |
9 | let ones = Array(6).fill(1);
10 | console.log(ones);
11 |
--------------------------------------------------------------------------------
/cap03/arrays/concat.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Metodo | Descricao
3 | * concat() |
4 | *
5 | */
6 |
7 | const zero = 0;
8 | const positiveNumbers = [1, 2, 3];
9 | const negativeNumbers = [-3, -2, -1];
10 | let numbers = negativeNumbers.concat(zero, positiveNumbers);
11 | console.log(numbers);
12 |
13 |
--------------------------------------------------------------------------------
/cap03/arrays/fibonnaci.js:
--------------------------------------------------------------------------------
1 | const fibonacci = [];
2 |
3 | fibonacci[1] = 1;
4 | fibonacci[2] = 1;
5 |
6 | for (let i = 3; i < 10; i++) {
7 | fibonacci[i] = fibonacci[i - 1] + fibonacci[i - 2];
8 | }
9 |
10 | for (let i = 1; i < fibonacci.length; i++) {
11 | console.log(fibonacci[i]);
12 | }
13 |
--------------------------------------------------------------------------------
/cap03/arrays/entries.js:
--------------------------------------------------------------------------------
1 | const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
2 |
3 | let aEntries = numbers.entries();
4 |
5 | // console.log(aEntries.next().value); // [0, 1] - position 0, value 1
6 |
7 | for (const number of aEntries) {
8 | console.log(number);
9 | }
10 |
11 |
12 |
--------------------------------------------------------------------------------
/cap03/arrays/initial-arrays.js:
--------------------------------------------------------------------------------
1 | let daysOfWeek = new Array();
2 | daysOfWeek = new Array(7);
3 | daysOfWeek = new Array(
4 | 'Sunday',
5 | 'Monday',
6 | 'Tuesday',
7 | 'Wednesday',
8 | 'Thursday',
9 | 'Friday',
10 | 'Saturday'
11 | );
12 |
13 | console.log(daysOfWeek.length);
14 | console.log(daysOfWeek);
15 |
--------------------------------------------------------------------------------
/cap02/template-literals.js:
--------------------------------------------------------------------------------
1 | const book = {
2 | name: 'Learning JavaScript DataStructures and Algorithms',
3 | };
4 |
5 | console.log(
6 | `You are reading ${book.name}.,\n and this is a new line\n and so is this.`
7 | );
8 | console.log(`You are reading ${book.name}.,
9 | and this is a new line
10 | and so is this.`);
11 |
--------------------------------------------------------------------------------
/cap01/loops.js:
--------------------------------------------------------------------------------
1 | console.log('for');
2 | for (let i = 0; i < 10; i++) {
3 | console.log(i);
4 | }
5 |
6 | console.log('while');
7 |
8 | let x = 0;
9 |
10 | while (x < 10) {
11 | console.log(x);
12 | x++;
13 | }
14 |
15 | console.log('do while');
16 |
17 | let y = 0;
18 | do {
19 | console.log(y);
20 | y++;
21 | } while (y < 10);
22 |
--------------------------------------------------------------------------------
/cap02/introduction-typescript/generics.ts:
--------------------------------------------------------------------------------
1 | interface Comparable1 {
2 | compareTo1(b: T): number;
3 | }
4 |
5 | class MyObject1 implements Comparable1 {
6 | age: number;
7 | compareTo1(b: MyObject): number {
8 | if (this.age === b.age) {
9 | return 0;
10 | }
11 | return this.age > b.age ? 1 : -1;
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/cap01/variables.js:
--------------------------------------------------------------------------------
1 | let num = 1
2 | num = 3
3 | let price = 14.5
4 | let myName = 'Will'
5 | let trueValue = true
6 | let nullVar = null
7 | let und;
8 |
9 | console.log('num: ' + num)
10 | console.log('myName: ' + myName)
11 | console.log('trueValue: ' + trueValue)
12 | console.log('price: ' + price)
13 | console.log('nullVar: ' + nullVar)
14 | console.log('und: ' + und)
--------------------------------------------------------------------------------
/cap03/arrays/arrays.js:
--------------------------------------------------------------------------------
1 | const averageTemJan = 31.9;
2 | const averageTemFev = 28.4;
3 | const averageTemMar = 29.9;
4 | const averageTemAbr = 25.5;
5 | const averageTemMai = 22.9;
6 | const averageTemJun = 19.7;
7 |
8 | const averageTem = [];
9 | averageTem[0] = 31.9;
10 | averageTem[1] = 28.4;
11 | averageTem[2] = 29.9;
12 | averageTem[3] = 25.5;
13 | averageTem[4] = 22.9;
14 | averageTem[5] = 19.7;
15 |
16 |
--------------------------------------------------------------------------------
/cap02/modules.js:
--------------------------------------------------------------------------------
1 | const circleArea = (r) => 3.14 * r ** 2;
2 | const squareArea = (s) => s * s;
3 |
4 | export { circleArea, squareArea };
5 |
6 | export const area = (r) => 3.14 * r * r;
7 | export const square = (s) => s * s;
8 |
9 | export default class Book {
10 | constructor(title) {
11 | this.title = title;
12 | }
13 |
14 | printTitle() {
15 | console.log(this.title);
16 | }
17 | }
18 |
19 |
--------------------------------------------------------------------------------
/cap03/arrays/@@iterator.js:
--------------------------------------------------------------------------------
1 | const numbers = [1, 2, 3, 4, 5];
2 |
3 | let iterator = numbers[Symbol.iterator]();
4 |
5 | console.log(iterator.next().value);
6 | console.log(iterator.next().value);
7 | console.log(iterator.next().value);
8 | console.log(iterator.next().value);
9 | console.log(iterator.next().value);
10 |
11 | iterator = numbers[Symbol.iterator]();
12 |
13 | for (const number of iterator) {
14 | console.log(number);
15 | }
--------------------------------------------------------------------------------
/cap01/functions.js:
--------------------------------------------------------------------------------
1 | function sayHello() {
2 | console.log('Hello');
3 | }
4 |
5 | sayHello();
6 |
7 | function output(text) {
8 | console.log(text);
9 | }
10 |
11 | output('Hello World');
12 |
13 | // apenas o primeiro argumento será utilizado, segundo argumento será ignorado
14 | output('Hello World', 'Test');
15 |
16 | function sum(num1, num2) {
17 | return num1 + num2;
18 | }
19 |
20 | let result = sum(1, 3);
21 | output(result);
22 |
--------------------------------------------------------------------------------
/cap01/scope-variables.js:
--------------------------------------------------------------------------------
1 | let myVariabel = 'global';
2 | myOtherVariabel = 'global';
3 | function myFunction() {
4 | let myVariabel = 'local';
5 | return myVariabel;
6 | }
7 |
8 | function myOtherFunction() {
9 | myOtherVariabel = 'local';
10 | return myOtherVariabel;
11 | }
12 |
13 | console.log(myVariabel);
14 | console.log(myFunction());
15 | console.log(myOtherVariabel);
16 | console.log(myOtherFunction());
17 | console.log(myOtherVariabel);
18 |
--------------------------------------------------------------------------------
/cap02/arrow-functions.js:
--------------------------------------------------------------------------------
1 | const circleAreaES5 = function circleArea(r) {
2 | let PI = 3.14;
3 | let area = PI * r * r;
4 | return area;
5 | };
6 |
7 | console.log(circleAreaES5(2));
8 |
9 | const circleArea = (r) => {
10 | const PI = 3.14;
11 | const area = PI * r * r;
12 | return area;
13 | };
14 |
15 | console.log(circleArea(2));
16 |
17 | const circleArea2 = (r) => 3.14 * r * r;
18 |
19 | console.log(circleArea2(2));
20 |
21 | const hello = () => console.log('hello');
22 |
23 | hello();
24 |
--------------------------------------------------------------------------------
/cap03/arrays/insert-array-first-position.js:
--------------------------------------------------------------------------------
1 | const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
2 |
3 | Array.prototype.insertFirstPosition = function (value) {
4 | for (let i = this.length; i >= 0; i--) {
5 | this[i] = this[i - 1];
6 | }
7 |
8 | this[0] = value;
9 | };
10 |
11 | numbers.insertFirstPosition(-1);
12 |
13 | console.log(numbers.length);
14 | console.log(numbers);
15 |
16 | numbers.unshift(-2);
17 | numbers.unshift(-4, -3);
18 |
19 | console.log(numbers.length);
20 | console.log(numbers);
21 |
--------------------------------------------------------------------------------
/cap03/arrays/re-index.js:
--------------------------------------------------------------------------------
1 | let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
2 |
3 | for (let i = 0; i < numbers.length; i++) {
4 | numbers[i] = numbers[i + 1];
5 | }
6 |
7 | console.log(numbers.length);
8 | console.log(numbers);
9 |
10 | module.exports = Array.prototype.reIndex = function (myArray) {
11 | const newArray = [];
12 |
13 | for (let i = 0; i < myArray.length; i++) {
14 | if (myArray[i] !== undefined) {
15 | newArray.push(myArray[i]);
16 | }
17 | }
18 |
19 | return newArray;
20 | };
21 |
22 |
23 |
--------------------------------------------------------------------------------
/cap03/arrays/remove-first-position.js:
--------------------------------------------------------------------------------
1 | const reIndex = require('./re-index');
2 |
3 | let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
4 |
5 | Array.prototype.removeFirstPosition = function () {
6 | for (let i = 0; i < this.length; i++) {
7 | this[i] = this[i + 1];
8 | }
9 |
10 | return reIndex(this);
11 | };
12 |
13 | numbers = numbers.removeFirstPosition();
14 |
15 | console.log(numbers.length);
16 | console.log(numbers);
17 |
18 |
19 | numbers.slice(5, 3)
20 |
21 | console.log(numbers.length)
22 | console.log(numbers)
--------------------------------------------------------------------------------
/cap03/arrays/pesquisa.js:
--------------------------------------------------------------------------------
1 | // let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
2 |
3 | // console.log(numbers.indexOf(10));
4 | // console.log(numbers.indexOf(100));
5 |
6 | // console.log(numbers.push(10));
7 |
8 | // console.log(numbers.lastIndexOf(10));
9 | // console.log(numbers.lastIndexOf(100));
10 |
11 | let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
12 |
13 | function multipleOf13(element, index, array) {
14 | return element % 13 === 0 ? true : false;
15 | }
16 |
17 | console.log(numbers.find(multipleOf13));
18 | console.log(numbers.findIndex(multipleOf13));
19 |
--------------------------------------------------------------------------------
/cap02/introduction-typescript/interfaces.ts:
--------------------------------------------------------------------------------
1 | interface Person {
2 | name: string;
3 | age: number;
4 | }
5 |
6 | function printName(person: Person) {
7 | console.log(person.name);
8 | }
9 |
10 | const john = { name: 'John', age: 21 };
11 | const mary = { name: 'Mary', age: 21, phone: '123-45678' };
12 | printName(john);
13 | printName(mary);
14 |
15 | interface Comparable {
16 | compareTo(b): number;
17 | }
18 |
19 | class MyObject implements Comparable {
20 | age: number;
21 | compareTo(b): number {
22 | if (this.age === b.age) {
23 | return 0;
24 | }
25 | return this.age > b.age ? 1 : -1;
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/cap02/rest-operators.js:
--------------------------------------------------------------------------------
1 | function sum(x, y, z) {
2 | return x + y + z;
3 | }
4 |
5 | const params = [3, 4, 5];
6 | /**
7 | * no ES2015, podemos usar o operador spread para passar um array de parametros
8 | */
9 | console.log(sum(...params));
10 |
11 | /**
12 | * no ES5, podemos usar o metodo apply para passar um array de parametros
13 | */
14 | console.log(sum.apply(undefined, params));
15 |
16 | function restParamaterFunction(x, y, ...a) {
17 | return (x + y) * a.length;
18 | }
19 |
20 | console.log(restParamaterFunction(1, 2, 'hello', true, 7)); // 9
21 |
22 | function restParamaterFunction2(x, y) {
23 | let a = Array.prototype.slice.call(arguments, 2);
24 | return (x + y) * a.length;
25 | }
26 |
27 | console.log(restParamaterFunction2(1, 2, 'hello', true, 7)); // 9
28 |
--------------------------------------------------------------------------------
/cap01/poo.js:
--------------------------------------------------------------------------------
1 | let obj = new Object();
2 |
3 | let objTwo = {};
4 |
5 | obj = {
6 | name: {
7 | first: 'Gandalf',
8 | last: 'the Grey',
9 | },
10 | address: 'Middle Earth',
11 | };
12 |
13 | console.log(obj);
14 |
15 | function Book(title, pages, isbn) {
16 | this.title = title;
17 | this.pages = pages;
18 | this.isbn = isbn;
19 | }
20 |
21 | let book = new Book('title', 'pag', 'isbn');
22 |
23 | console.log(book.title);
24 | book.title = 'new title';
25 | console.log(book.title);
26 |
27 | Book.prototype.printTitle = function () {
28 | console.log(this.title);
29 | };
30 |
31 | book.printTitle();
32 |
33 | function Book(title, pages, isbn) {
34 | this.title = title;
35 | this.pages = pages;
36 | this.isbn = isbn;
37 | this.printIbsn = function () {
38 | console.log(this.isbn);
39 | };
40 | }
41 |
42 | book.printIbsn();
43 |
--------------------------------------------------------------------------------
/cap02/values-default-parameters-func.js:
--------------------------------------------------------------------------------
1 | /**
2 | * com ES2015, podemos definir valores padrao para os parametros de uma funcao
3 | */
4 |
5 | function sum(x = 1, y = 2, z = 3) {
6 | return x + y + z;
7 | }
8 |
9 | console.log(sum(4, 2));
10 |
11 | /**
12 | * sem ES2015, podemos definir valores padrao para os parametros de uma funcao
13 | */
14 |
15 | function sum2(x, y, z) {
16 | if (x === undefined) x = 1;
17 | if (y === undefined) y = 2;
18 | if (z === undefined) z = 3;
19 | return x + y + z;
20 | }
21 |
22 | console.log(sum2(4, 2));
23 |
24 | function sum3() {
25 | let x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
26 | let y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;
27 | let z = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 3;
28 | return x + y + z;
29 | }
30 |
31 | console.log(sum3(4, 2));
32 |
--------------------------------------------------------------------------------
/cap02/property-of-objets.js:
--------------------------------------------------------------------------------
1 | /**
2 | * ES6 destructuring array
3 | */
4 |
5 | let [x, y] = ['a', 'b'];
6 |
7 | console.log(x); // a
8 |
9 | let q = 'a';
10 | let w = 'b';
11 |
12 | /**
13 | * ES5 swap variables
14 | */
15 | [q, w] = [w, q];
16 |
17 | let temp = q;
18 |
19 | q = w;
20 | w = temp;
21 |
22 | /**
23 | * porperty shorthand
24 | */
25 |
26 | let [a, b] = ['a', 'b'];
27 | let obj = { x, y };
28 |
29 | console.log(obj); // { x: 'a', y: 'b' }
30 |
31 | let p = 'a';
32 | let t = 'b';
33 |
34 | let obj2 = { p, t };
35 |
36 | console.log(obj2); // { p: 'a', t: 'b' }
37 |
38 | const hello = {
39 | name: 'abcdef',
40 | printHello() {
41 | console.log('Hello');
42 | },
43 | };
44 |
45 | console.log(hello.printHello()); // Hello
46 |
47 | const hello2 = {
48 | name: 'abcdef',
49 | printHello: function () {
50 | console.log('Hello');
51 | },
52 | };
53 |
54 | console.log(hello2.printHello()); // Hello
55 |
--------------------------------------------------------------------------------
/cap01/true-and-false.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Tipo de valor | Resultado
3 | * undefined | false
4 | * null | false
5 | * Boolean | O valor do booleano
6 | * Number | false se +0, -0, ou NaN; caso contrário, true
7 | * String | false se string vazia; caso contrário, true
8 | *
9 | */
10 |
11 |
12 | function testTruthy(val) {
13 | return val ? console.log('truthy') : console.log('falsy');
14 | }
15 |
16 | testTruthy(true); // true
17 | testTruthy(false); // false
18 | testTruthy(new Boolean(false)); // true (object is always true)
19 | testTruthy(''); // false
20 | testTruthy('Packt'); // true
21 | testTruthy(new String('')); // true (object is always true)
22 | testTruthy(1); // true
23 | testTruthy(-1); // true
24 | testTruthy(NaN); // false
25 | testTruthy(new Number(NaN)); // true (object is always true)
26 | testTruthy({}); // true (object is always true)
27 | var obj = { name: 'John' };
28 | testTruthy(obj); // true
29 | testTruthy(obj.name); // true
30 | testTruthy(obj.age); // false (age does not exist)
--------------------------------------------------------------------------------
/cap03/arrays/array-two-dimensional-and-multidimensional.js:
--------------------------------------------------------------------------------
1 | let averageTempDay1 = [72, 75, 79, 79, 81, 81];
2 | let averageTempDay2 = [81, 79, 75, 75, 73, 72];
3 |
4 | let averageTemp = [];
5 |
6 | averageTemp[0] = averageTempDay1;
7 | averageTemp[1] = averageTempDay2;
8 |
9 | console.log(averageTemp);
10 |
11 | function printMatrix(myMatrix) {
12 | for (let i = 0; i < myMatrix.length; i++) {
13 | for (let j = 0; j < myMatrix[i].length; j++) {
14 | console.log(myMatrix[i][j]);
15 | }
16 | }
17 | }
18 |
19 | printMatrix(averageTemp);
20 |
21 | const matrix3x3x3 = [];
22 |
23 | for (let i = 0; i < 3; i++) {
24 | matrix3x3x3[i] = [];
25 | for (let j = 0; j < 3; j++) {
26 | matrix3x3x3[i][j] = [];
27 | for (let z = 0; z < 3; z++) {
28 | matrix3x3x3[i][j][z] = i + j + z;
29 | }
30 | }
31 | }
32 |
33 | for (let i = 0; i < matrix3x3x3.length; i++) {
34 | for (let j = 0; j < matrix3x3x3[i].length; j++) {
35 | for (let z = 0; z < matrix3x3x3[i][j].length; z++) {
36 | console.log(matrix3x3x3[i][j][z]);
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/cap01/instructions-conditions.js:
--------------------------------------------------------------------------------
1 | let num;
2 |
3 | num = 1;
4 |
5 | if (num === 1) {
6 | console.log('num is equal to 1');
7 | }
8 |
9 | // let num = 0;
10 |
11 | // if (num === 1) {
12 | // console.log('num is equal to 1');
13 | // } else {
14 | // console.log('num is not equal to 1, the value of num is ' + num);
15 | // }
16 |
17 | // if (num === 1) {
18 | // num--;
19 | // } else {
20 | // num++;
21 | // }
22 |
23 | num == 1 ? num-- : num++;
24 |
25 | // let month = 5;
26 | // if (month === 1) {
27 | // console.log('January');
28 | // } else if (month === 2) {
29 | // console.log('February');
30 | // } else if (month === 3) {
31 | // console.log('March');
32 | // } else {
33 | // console.log('Month is not January, February or March');
34 | // }
35 |
36 | let month = 5;
37 |
38 | switch (month) {
39 | case 1:
40 | console.log('January');
41 | break;
42 | case 2:
43 | console.log('February');
44 | break;
45 | case 3:
46 | console.log('March');
47 | break;
48 | default:
49 | console.log('Month is not January, February or March');
50 | break;
51 | }
52 |
--------------------------------------------------------------------------------
/cap03/arrays/sort.js:
--------------------------------------------------------------------------------
1 | const numbers = [2, 3, 1, 5, 4];
2 |
3 | // console.log(numbers.sort());
4 | // console.log(numbers.sort((a, b) => a - b));
5 |
6 | function compareNumbers(a, b) {
7 | if (a < b) {
8 | return -1;
9 | }
10 |
11 | if (a > b) {
12 | return 1;
13 | }
14 |
15 | return 0;
16 | }
17 |
18 | console.log(numbers.sort(compareNumbers));
19 |
20 | const friends = [
21 | {
22 | name: 'John',
23 | age: 30,
24 | },
25 | {
26 | name: 'Ana',
27 | age: 20,
28 | },
29 | {
30 | name: 'Chris',
31 | age: 25,
32 | },
33 | ];
34 |
35 | function comparePerson(a, b) {
36 | if (a.age < b.age) {
37 | return -1;
38 | }
39 |
40 | if (a.age > b.age) {
41 | return 1;
42 | }
43 |
44 | return 0;
45 | }
46 |
47 | console.log(friends.sort(comparePerson));
48 |
49 | let names = ['Ana', 'John', 'john', 'ana'];
50 |
51 | function compareStrings(a, b) {
52 | if (a.toLowerCase() < b.toLowerCase()) {
53 | return -1;
54 | }
55 |
56 | if (a.toLowerCase() > b.toLowerCase()) {
57 | return 1;
58 | }
59 |
60 | return 0;
61 | }
62 |
63 | console.log(names.sort(compareStrings));
64 |
--------------------------------------------------------------------------------
/cap02/let-const.js:
--------------------------------------------------------------------------------
1 | var framework = 'Angular';
2 | var framework = 'React';
3 | console.log(framework); // React
4 |
5 | let language = 'JavaScript';
6 | // let language = 'Ruby'; SyntaxError: Identifier 'language' has already been declared
7 |
8 | console.log(language);
9 |
10 | const PI = 3.141593;
11 | // PI = 3.14; // TypeError: Assignment to constant variable.
12 | console.log(PI);
13 |
14 | const jsFramework = {
15 | name: 'Angular',
16 | };
17 |
18 | jsFramework.name = 'React';
19 |
20 | // jsFramework = {
21 | // name: 'Vue',
22 | // }; // TypeError: Assignment to constant variable.
23 |
24 | let movie = 'Lord of the Rings';
25 | // let movie = 'Batman v Superman';// SyntaxError: Identifier 'movie' has already been declared
26 |
27 | function starWarsFan() {
28 | const movie = 'Star Wars';
29 | return movie;
30 | }
31 |
32 | function marvelFan() {
33 | movie = 'The Avengers';
34 | return movie;
35 | }
36 |
37 | function blizzardFan() {
38 | const isFan = true;
39 | let phrase = 'Warcraft';
40 | console.log('Before if: ' + phrase);
41 | if (isFan) {
42 | let phrase = 'initial text';
43 | phrase = 'For the Horde!';
44 | console.log('Inside if: ' + phrase);
45 | }
46 | phrase = 'For the Alliance!';
47 | console.log('After if: ' + phrase);
48 | }
49 |
50 | console.log(movie)
51 | console.log(starWarsFan())
52 | console.log(marvelFan())
53 | console.log(movie)
54 | blizzardFan()
--------------------------------------------------------------------------------
/cap02/poo-with-class.js:
--------------------------------------------------------------------------------
1 | /**
2 | * ES2015 tambem introduziu uma maneira mais limpa de declarar classes.
3 | */
4 |
5 | function Book(title, pages, isbn) {
6 | this.title = title;
7 | this.pages = pages;
8 | this.isbn = isbn;
9 | }
10 |
11 | Book.prototype.printTitle = function () {
12 | console.log(this.title);
13 | }
14 |
15 | /**
16 | * com ES1025 podemos simplificar
17 | */
18 |
19 | class Book2 {
20 | constructor(title, pages, isbn) {
21 | this.title = title;
22 | this.pages = pages;
23 | this.isbn = isbn;
24 | }
25 |
26 | printIsbn() {
27 | console.log(this.isbn);
28 | }
29 | }
30 |
31 | let book = new Book2('title', 'pag', 'isbn');
32 | console.log(book.title);
33 | book.title = 'new title';
34 | console.log(book.title);
35 |
36 | class ITBook extends Book2 {
37 | constructor(title, pages, isbn, technology) {
38 | super(title, pages, isbn);
39 | this.technology = technology;
40 | }
41 |
42 | printTechnology() {
43 | console.log(this.technology);
44 | }
45 | }
46 |
47 | let jsBook = new ITBook('Learning JS Algorithms', '200', '1234567890', 'JavaScript');
48 | console.log(jsBook.title);
49 | console.log(jsBook.printTechnology());
50 |
51 | /**
52 | * trabalhando com getters e setters
53 | */
54 |
55 | class Person {
56 | constructor(name) {
57 | this._name = name;
58 | }
59 |
60 | get name() {
61 | return this._name;
62 | }
63 |
64 | set name(value) {
65 | this._name = value;
66 | }
67 | }
68 |
69 | let lotrChar = new Person('Frodo');
70 | console.log(lotrChar.name);
71 | lotrChar.name = 'Gandalf';
72 | console.log(lotrChar.name);
--------------------------------------------------------------------------------
/cap01/functions-operators-equals.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Type(x) | Type(y) | Result
3 | * null | null | true
4 | * undefined | null | true
5 | * Number | String | x == toNumber(y)
6 | * String | Number | toNumber(x) == y
7 | * Boolean | Any | toNumber(x) == y
8 | * Any | Boolean | x == toNumber(y)
9 | * String|Number | Object | x == toPrimitive(y)
10 | * Object | String|Number | toPrimitive(x) == y
11 | */
12 |
13 | /**
14 | * Tipo de valor | Resultado
15 | * undefined | E NaN
16 | * null | E +0
17 | * Boolean | Se for true, é 1; se for false, é +0
18 | * Number | O valor numérico
19 | * Object | Se o valueOf() devolver um valor primitivo, usa esse valor primitivo sera devolvido;
20 | * caso contrário, usa o toString() devolver um valor primitivo, usa esse valor primitivo sera devolvido; se não, gera um erro
21 | */
22 |
23 | /**
24 | * sabemos que a saida do codigo a seguir eh true (tamanho da string > 1)
25 | */
26 | console.log('Packt' ? true : false); // true
27 |
28 | /**
29 | * o valor boolean eh convertido com toNumber, portanto temos pack == 1
30 | * e em seguida, o valor de string, eh convertido com toNumber.
31 | * Como a string eh construida de caracteres alfabeticos, NaN sera devolvido, portanto temos NaN == 1, que eh false.
32 | */
33 | console.log('packt' == true); // false
34 |
35 | /**
36 | * o valor boolean eh invertido com toNumber, por tanto temos pack == 0
37 | * e em seguida, o valor de string, eh convertido com toNumber.
38 | * Como a string eh construida de caracteres alfabeticos, NaN sera devolvido, portanto temos NaN == 0, que eh false.
39 | */
40 | console.log('packt' == false);
41 |
42 | /**
43 | * Type(x) | Valores | Resultado
44 | * Number | x tem o mesmo valor que y (mas nao eh NaN) | true
45 | * String | x e y tem caracteres identicos | true
46 | * Boolean | x e y sao ambos true ou ambos false | true
47 | * Object | x e y referem-se ao mesmo objeto | true
48 | */
49 |
50 | console.log('packt' === true); // true
51 | console.log('packt' === 'packt'); // true
52 | let person = { name: 'John' };
53 | let anotherPerson = { name: 'John' };
54 | console.log(person == anotherPerson); // false, pois sao objetos diferentes
55 |
--------------------------------------------------------------------------------
/cap01/operators.js:
--------------------------------------------------------------------------------
1 | let num = 0;
2 | num = num + 2;
3 | num = num * 3;
4 | num = num / 2;
5 | num++;
6 | num--;
7 | num += 1;
8 | num -= 2;
9 | num *= 3;
10 | num /= 2;
11 | num %= 3;
12 |
13 | console.log('num == 1 : ' + (num == 1));
14 | console.log('num === 1 : ' + (num === 1));
15 | console.log('num != 1 : ' + (num != 1));
16 | console.log('num > 1 : ' + (num > 1));
17 | console.log('num < 1 : ' + (num < 1));
18 | console.log('num >= 1 : ' + (num >= 1));
19 | console.log('num <= 1 : ' + (num <= 1));
20 | console.log('true && false : ' + (true && false));
21 | console.log('true || false : ' + (true || false));
22 | console.log('!true : ' + !true);
23 |
24 | /**
25 | * Operador aritmético | Descrição
26 | * + | Adição
27 | * - | Subtração
28 | * * | Multiplicação
29 | * / | Divisão
30 | * % | Resto
31 | * ++ | Incremento
32 | * -- | Decremento
33 | */
34 |
35 | /**
36 | * Operador de atribuicao | Descrição
37 | * = | Atribuição
38 | * += | Adição (x+=y é o mesmo que x = x + y)
39 | * -= | Subtração (x-=y é o mesmo que x = x - y)
40 | * *= | Multiplicação (x*=y é o mesmo que x = x * y)
41 | * /= | Divisão (x/=y é o mesmo que x = x / y)
42 | * %= | Resto (x%=y é o mesmo que x = x % y)
43 | */
44 |
45 | /**
46 | * Operador de comparação | Descrição
47 | * == | Igual a
48 | * === | Igual a (valor e tipo)
49 | * != | Diferente de
50 | * !== | Diferente de (valor e tipo)
51 | * > | Maior que
52 | * < | Menor que
53 | * >= | Maior ou igual a
54 | * <= | Menor ou igual a
55 | */
56 |
57 | /**
58 | * Operador lógico | Descrição
59 | * && | E
60 | * || | Ou
61 | * ! | Não
62 | */
63 |
64 | console.log('5 & 1:', 5 & 1);
65 | console.log('5 | 1:', 5 | 1);
66 | console.log('~ 5:', ~5);
67 | console.log('5 ^ 1:', 5 ^ 1);
68 | console.log('5 << 1:', 5 << 1);
69 | console.log('5 >> 1:', 5 >> 1);
70 |
71 | /**
72 | * Operador bitwise | Descrição
73 | * & | E
74 | * | | Ou
75 | * ~ | Não
76 | * ^ | Ou exclusivo (XOR)
77 | * << | Deslocamento a esquerda
78 | * >> | Deslocamento a direita
79 | */
80 |
81 | console.log('typeof num:', typeof num);
82 | console.log('typeof Packt:', typeof 'Packt');
83 | console.log('typeof true:', typeof true);
84 | console.log('typeof [1,2,3]:', typeof [1, 2, 3]);
85 | console.log('typeof {name:John}:', typeof { name: 'John' });
86 |
87 | let myObj = { name: 'John', age: 22 };
88 | delete myObj.age;
89 |
90 | console.log('myObj:', myObj);
91 |
--------------------------------------------------------------------------------
/cap03/arrays/README.md:
--------------------------------------------------------------------------------
1 | # Arrays
2 |
3 | ## Referencias para metodos de array em JavaScript
4 |
5 | | Metodo | Descricao |
6 | | ----------- | ------------------------------------------------------------------------------------------------------------------------------------ |
7 | | concat | Junta varios arrays e devolve uma copia dos arrays concatenados. |
8 | | every | Intera por todos os elementos do array, verificando uma condicao desejada (funcao) ate que `false` seja devolvido. |
9 | | filter | Cria um array com todos os elementos avaliados com `true` de uma funcao especificada. |
10 | | forEach | Executa uma funcao especifica em cada elemento do array. |
11 | | join | Reune todos os elementos do array em uma string. |
12 | | indexOf | Pesquisa o array em busca de elementos especificos e devolve sua posicao. |
13 | | lastIndexOf | Devolve a posicao do ultimo item do array que corresponda ao criterio de pesquisa. |
14 | | map | Cria outro array a partir de uma funcao que contem o criterio/condicao e devolve os elementos do array que correspondem ao criterio. |
15 | | reverse | Inverte o array, de modo que o ultimo item se torna o primiero, e vice-versa. |
16 | | slice | Devolve um novo array a partir de um indice especifico. |
17 | | some | Intera por todos os elementos do array, verificando a condicao desejada (funcao) ate que `true` seja devolvido. |
18 | | sort | Organiza o attay em ordem alfabetica ou de acordo com a funcao especifica. |
19 | | toString | Devolve o array na forma de string. |
20 | | valueOf | E semelhante ao metodo toString e devolve o array em forma de uma string. |
21 |
22 | # ECMAScript 6 e as novas funcionalidades de array
23 |
24 | | Metodo | Descricao |
25 | | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
26 | | @@interator | Devolve um objeto que contem os pares chave/valor do array; pode ser chamado sincornamente para obter a chave/valor dos elementos do array. |
27 | | copyWithin | Copia uma sequencia de valores do arrtay na posicao de um indice de inicio. |
28 | | entries | Devolve @@interator, que contem pares chave/valor. |
29 | | includes | Devolve `true` caso um elemento seja encontrado no array, e false ao contrario. Foi adicionado na ES2016. |
30 | | find | Busca um elemento no array, dada uma condicao desejada (funcao de callback), e devolve o elemento caso seja encontrado. |
31 | | findIndex | Busca um elemento no array. dada uma condicao desejada (funcao de callback), e devolve o indice do elemento caso seja encontrado. |
32 | | fill | Preenche o array com um valor estatico. |
33 | | from | Cria um novo array a partir de um array existente. |
34 | | keys | Devolve um @@interaror, contendo as chaves do arrays. |
35 | | of | Cria um novo array a partir dos argumentos passados para o metodo. |
36 | | values | Devolve @@interaror, contendo os valores do array. |
37 |
38 | # Classe TypedArray
39 |
40 | | TypedArray | Descricao |
41 | | ----------------- | --------------------------------------------------------- |
42 | | Int8Array | Inteiro de 8 bits com sinal, usando complemento de dois. |
43 | | Uint8Array | Inteiro de 8 bits sem sinal. |
44 | | Uint8ClampedArray | Inteiro de 8 bits sem sinal. |
45 | | Int16Array | Inteiro de 16 bits com sinal, usando complemento de dois. |
46 | | Uint16Array | Inteiro de 16 bits sem sinal. |
47 | | Int32Array | Inteiro de 32 bits com sinal, usando complemento de dois. |
48 | | Uint32Array | Inteiro de 32 bits sem sinal. |
49 | | Float32Array | Numero de ponto flutuante padrao IEEE com 32 bits. |
50 | | Float64Array | Numero de ponto flutuante padrao IEEE com 64 bits. |
51 |
--------------------------------------------------------------------------------