├── .gitignore ├── basics-i ├── day1 │ ├── external_script.ts │ ├── external_script.js │ ├── another_external_script.ts │ ├── another_external_script.js │ ├── main.js │ ├── main.ts │ └── index.html ├── day24 │ ├── images │ │ ├── earth.png │ │ ├── mars.png │ │ ├── moon.png │ │ ├── pluto.png │ │ ├── venus.png │ │ ├── galaxy.gif │ │ ├── jupiter.png │ │ ├── mercury.png │ │ ├── neptune.png │ │ ├── saturn.png │ │ └── uranus.png │ ├── index.html │ └── scripts │ │ ├── main.js │ │ └── main.ts ├── day20 │ └── main.ts ├── day3 │ ├── password.js │ ├── password.ts │ ├── triangle.js │ ├── triangle.ts │ ├── main.html │ ├── time.ts │ ├── time.js │ ├── main.js │ └── main.ts ├── day21 │ ├── main.html │ ├── main.js │ └── main.ts ├── day4 │ ├── daysInMonth.js │ ├── daysInMonth.ts │ ├── main.ts │ └── main.js ├── day22 │ ├── main.html │ ├── main2.html │ └── main3.html ├── day23 │ ├── main5.html │ ├── main6.html │ ├── main2.html │ ├── main3.html │ ├── main4.html │ └── main.html ├── day19 │ ├── main.js │ └── main.ts ├── day14 │ ├── main.ts │ └── main.js ├── day7 │ ├── main.ts │ └── main.js ├── day17 │ ├── main.js │ └── main.ts ├── day2 │ ├── main.js │ └── main.ts ├── day5 │ ├── main.js │ └── main.ts ├── day10 │ ├── main.ts │ └── main.js ├── day6 │ ├── main.ts │ └── main.js ├── day11 │ ├── main.ts │ └── main.js ├── day16 │ ├── main.js │ └── main.ts ├── day13 │ ├── main.ts │ └── main.js ├── day12 │ ├── main.js │ └── main.ts ├── day18 │ ├── main.ts │ └── main.js ├── day15 │ ├── main.ts │ └── main.js ├── day9 │ ├── main.ts │ └── main.js └── day8 │ ├── main.js │ └── main.ts ├── package.json ├── tsconfig.json ├── .eslintrc ├── README.md └── overview ├── main.ts └── main.js /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ -------------------------------------------------------------------------------- /basics-i/day1/external_script.ts: -------------------------------------------------------------------------------- 1 | console.log('This is the external script log') -------------------------------------------------------------------------------- /basics-i/day1/external_script.js: -------------------------------------------------------------------------------- 1 | console.log('This is the external script log'); 2 | -------------------------------------------------------------------------------- /basics-i/day1/another_external_script.ts: -------------------------------------------------------------------------------- 1 | console.log('This is ANOTHER external script log') -------------------------------------------------------------------------------- /basics-i/day1/another_external_script.js: -------------------------------------------------------------------------------- 1 | console.log('This is ANOTHER external script log'); 2 | -------------------------------------------------------------------------------- /basics-i/day24/images/earth.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eugeneyan/learning-typescript/HEAD/basics-i/day24/images/earth.png -------------------------------------------------------------------------------- /basics-i/day24/images/mars.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eugeneyan/learning-typescript/HEAD/basics-i/day24/images/mars.png -------------------------------------------------------------------------------- /basics-i/day24/images/moon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eugeneyan/learning-typescript/HEAD/basics-i/day24/images/moon.png -------------------------------------------------------------------------------- /basics-i/day24/images/pluto.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eugeneyan/learning-typescript/HEAD/basics-i/day24/images/pluto.png -------------------------------------------------------------------------------- /basics-i/day24/images/venus.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eugeneyan/learning-typescript/HEAD/basics-i/day24/images/venus.png -------------------------------------------------------------------------------- /basics-i/day24/images/galaxy.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eugeneyan/learning-typescript/HEAD/basics-i/day24/images/galaxy.gif -------------------------------------------------------------------------------- /basics-i/day24/images/jupiter.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eugeneyan/learning-typescript/HEAD/basics-i/day24/images/jupiter.png -------------------------------------------------------------------------------- /basics-i/day24/images/mercury.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eugeneyan/learning-typescript/HEAD/basics-i/day24/images/mercury.png -------------------------------------------------------------------------------- /basics-i/day24/images/neptune.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eugeneyan/learning-typescript/HEAD/basics-i/day24/images/neptune.png -------------------------------------------------------------------------------- /basics-i/day24/images/saturn.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eugeneyan/learning-typescript/HEAD/basics-i/day24/images/saturn.png -------------------------------------------------------------------------------- /basics-i/day24/images/uranus.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eugeneyan/learning-typescript/HEAD/basics-i/day24/images/uranus.png -------------------------------------------------------------------------------- /basics-i/day20/main.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Code style guidelines: https://github.com/Asabeneh/30-Days-Of-JavaScript/blob/master/20_Day_Writing_clean_codes/20_day_writing_clean_codes.md 3 | */ -------------------------------------------------------------------------------- /basics-i/day3/password.js: -------------------------------------------------------------------------------- 1 | var password = prompt('Enter your password'); 2 | password.length < 7 3 | ? alert('Password is too short! (must be at least 7 chars)') 4 | : alert('Password accepted!'); 5 | -------------------------------------------------------------------------------- /basics-i/day3/password.ts: -------------------------------------------------------------------------------- 1 | let password: string = prompt('Enter your password') 2 | 3 | password.length < 7 4 | ? alert('Password is too short! (must be at least 7 chars)') 5 | : alert('Password accepted!') -------------------------------------------------------------------------------- /basics-i/day3/triangle.js: -------------------------------------------------------------------------------- 1 | var base = parseFloat(prompt('Enter base of triangle')); 2 | var height = parseFloat(prompt('Height of triangle')); 3 | var area = 0.5 * base * height; 4 | alert("The area of your triangle is " + area); 5 | -------------------------------------------------------------------------------- /basics-i/day3/triangle.ts: -------------------------------------------------------------------------------- 1 | let base: number = parseFloat(prompt('Enter base of triangle')) 2 | let height: number = parseFloat(prompt('Height of triangle')) 3 | 4 | let area = 0.5 * base * height 5 | 6 | alert(`The area of your triangle is ${area}`) -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "dependencies": { 3 | "node-fetch": "^2.6.1", 4 | "node-localstorage": "^2.1.6", 5 | "typescript": "^4.2.1-rc" 6 | }, 7 | "devDependencies": { 8 | "@types/node": "^14.14.31", 9 | "html-loader": "^2.1.1" 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "esnext", 4 | "target": "es2017", 5 | "lib": [ 6 | "esnext", 7 | "dom" 8 | ], 9 | "downlevelIteration": true, 10 | "strict": true 11 | } 12 | } -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "plugins": [ 3 | "@typescript-eslint" 4 | ], 5 | "rules": { 6 | "semi": [ 7 | "error", 8 | "never" 9 | ], 10 | "quotes": [ 11 | 2, 12 | "single" 13 | ] 14 | }, 15 | "parserOptions": { 16 | "ecmaVersion": 2017 17 | }, 18 | "env": { 19 | "es6": true 20 | } 21 | } -------------------------------------------------------------------------------- /basics-i/day21/main.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Document Object Model 6 | 7 | 8 | 9 | 10 |

First Title

11 |

Second Title

12 |

Third Title

13 |

14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /basics-i/day4/daysInMonth.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | exports.__esModule = true; 3 | function getMonthFromString(month_string) { 4 | return new Date(Date.parse(month + ' 1, 2020')).getMonth() + 1; 5 | } 6 | function getDaysInMonth(month) { 7 | var month_int = getMonthFromString(month); 8 | return new Date(2020, month_int, 0).getDate(); 9 | } 10 | var month = 'November'; 11 | console.log(month + " has " + getDaysInMonth(month) + " days"); 12 | -------------------------------------------------------------------------------- /basics-i/day22/main.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Document Object Model:30 Days Of JavaScript 7 | 8 | 9 | 10 | 11 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /basics-i/day23/main5.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Document Object Model:30 Days Of JavaScript 6 | 7 | 8 | 9 |

Data Binding using input or change event

10 | 11 | 12 |

13 | 14 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /basics-i/day1/main.js: -------------------------------------------------------------------------------- 1 | console.log('Hello World!'); 2 | console.log(3 / 2); 3 | console.log(3 % 2); 4 | console.log(5 / 3); 5 | console.log(5 % 3); 6 | console.log(Math.pow(2, 4)); 7 | var undefinedValue; 8 | console.log(undefinedValue); 9 | var emptyValue = null; 10 | console.log(emptyValue); 11 | var firstName = 'Eugene'; 12 | var lastName = 'Yan'; 13 | var country = 'US'; 14 | var city = 'Seattle'; 15 | var age = 34; 16 | var isMarried = true; 17 | console.log(firstName, lastName, country, city, age, isMarried); 18 | // This is a single line comment 19 | /* This is a 20 | multi-line 21 | comment 22 | */ 23 | -------------------------------------------------------------------------------- /basics-i/day1/main.ts: -------------------------------------------------------------------------------- 1 | console.log('Hello World!') 2 | 3 | console.log(3 / 2) 4 | 5 | console.log(3 % 2) 6 | 7 | console.log(5 / 3) 8 | console.log(5 % 3) 9 | 10 | console.log(2 ** 4) 11 | 12 | let undefinedValue 13 | console.log(undefinedValue) 14 | 15 | let emptyValue = null 16 | console.log(emptyValue) 17 | 18 | let firstName = 'Eugene' 19 | let lastName = 'Yan' 20 | let country = 'US' 21 | let city = 'Seattle' 22 | let age = 34 23 | let isMarried = true 24 | 25 | console.log(firstName, lastName, country, city, age, isMarried) 26 | 27 | // This is a single line comment 28 | 29 | /* This is a 30 | multi-line 31 | comment 32 | */ -------------------------------------------------------------------------------- /basics-i/day23/main6.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Document Object Model:30 Days Of JavaScript 6 | 7 | 8 | 9 |

Giving feedback using blur event

10 | 11 | 12 |

13 | 14 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /basics-i/day22/main2.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Document Object Model:30 Days Of JavaScript 6 | 7 | 8 | 9 | 10 | 21 | 22 | -------------------------------------------------------------------------------- /basics-i/day23/main2.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Document Object Model 6 | 7 | 8 | 9 | 10 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /basics-i/day23/main3.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Document Object Model 6 | 7 | 8 | 9 | 10 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /basics-i/day3/main.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Day3 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /basics-i/day3/time.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Exercises Level 3 3 | * Create a human readable time format using the Date time object. 4 | * The hour and the minute should be all the time two digits 5 | * (7 hours should be 07 and 5 minutes should be 05) 6 | * E.g., YYYY-MM-DD HH:mm eg. 20120-01-02 07:05 7 | */ 8 | let timeNow = new Date() 9 | 10 | function padNum(num: Number) { 11 | return num.toString().padEnd(2, '0') 12 | } 13 | 14 | let year = timeNow.getFullYear() 15 | let month = padNum(timeNow.getMonth() + 1) 16 | let day = padNum(timeNow.getDate()) 17 | let hour = padNum(timeNow.getHours()) 18 | let minute = padNum(timeNow.getMinutes()) 19 | 20 | console.log(`Time now: ${year}-${month}-${day} ${hour}:${minute}`) -------------------------------------------------------------------------------- /basics-i/day1/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 30DaysOfScript 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | let firstName 21 | console.log(firstName) 22 | 23 | let emptyValue = null 24 | console.log(emptyValue) 25 | 26 | 27 | -------------------------------------------------------------------------------- /basics-i/day3/time.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Exercises Level 3 3 | * Create a human readable time format using the Date time object. 4 | * The hour and the minute should be all the time two digits 5 | * (7 hours should be 07 and 5 minutes should be 05) 6 | * E.g., YYYY-MM-DD HH:mm eg. 20120-01-02 07:05 7 | */ 8 | var timeNow = new Date(); 9 | function padNum(num) { 10 | return num.toString().padEnd(2, '0'); 11 | } 12 | var year = timeNow.getFullYear(); 13 | var month = padNum(timeNow.getMonth() + 1); 14 | var day = padNum(timeNow.getDate()); 15 | var hour = padNum(timeNow.getHours()); 16 | var minute = padNum(timeNow.getMinutes()); 17 | console.log("Time now: " + year + "-" + month + "-" + day + " " + hour + ":" + minute); 18 | -------------------------------------------------------------------------------- /basics-i/day4/daysInMonth.ts: -------------------------------------------------------------------------------- 1 | /* Write a program which tells the number of days in a month. 2 | 3 | Enter a month: January 4 | January has 31 days. 5 | 6 | Enter a month: JANUARY 7 | January has 31 day 8 | 9 | Enter a month: February 10 | February has 28 days. 11 | 12 | Enter a month: FEbruary 13 | February has 28 days. 14 | 15 | */ 16 | export { } 17 | 18 | function getMonthFromString(month_string: string) { 19 | return new Date(Date.parse(month + ' 1, 2020')).getMonth() + 1 20 | } 21 | 22 | function getDaysInMonth(month: string) { 23 | let month_int = getMonthFromString(month) 24 | return new Date(2020, month_int, 0).getDate() 25 | } 26 | 27 | let month: string = 'November' 28 | console.log(`${month} has ${getDaysInMonth(month)} days`) -------------------------------------------------------------------------------- /basics-i/day23/main4.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Document Object Model:30 Days Of JavaScript 6 | 7 | 8 | 9 |

Body Mass Index Calculator

10 | 11 | 12 | 13 | 14 | 15 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /basics-i/day19/main.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Javascript allows the writing of functions inside an outer function. 3 | * If an inner function accesses the variables of the outer function, it's call a closure. 4 | */ 5 | function outerFunction() { 6 | var count = 0; 7 | function innerFunction() { 8 | count++; 9 | return count; 10 | } 11 | return innerFunction; 12 | } 13 | var innerFunc = outerFunction(); 14 | console.log(innerFunc()); 15 | console.log(innerFunc()); 16 | console.log(innerFunc()); 17 | function outerFunction2() { 18 | var count = 0; 19 | function plusOne() { 20 | count++; 21 | return count; 22 | } 23 | function minusOne() { 24 | count--; 25 | return count; 26 | } 27 | return { 28 | plusOne: plusOne(), 29 | minusOne: minusOne() 30 | }; 31 | } 32 | var innerFuncs = outerFunction2(); 33 | console.log(innerFuncs.plusOne); 34 | console.log(innerFuncs.minusOne); 35 | -------------------------------------------------------------------------------- /basics-i/day19/main.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Javascript allows the writing of functions inside an outer function. 3 | * If an inner function accesses the variables of the outer function, it's call a closure. 4 | */ 5 | 6 | function outerFunction() { 7 | let count = 0 8 | function innerFunction() { 9 | count++ 10 | return count 11 | } 12 | return innerFunction 13 | } 14 | 15 | const innerFunc = outerFunction() 16 | console.log(innerFunc()) 17 | console.log(innerFunc()) 18 | console.log(innerFunc()) 19 | 20 | function outerFunction2() { 21 | let count = 0 22 | function plusOne() { 23 | count++ 24 | return count 25 | } 26 | 27 | function minusOne() { 28 | count-- 29 | return count 30 | } 31 | 32 | return { 33 | plusOne: plusOne(), 34 | minusOne: minusOne() 35 | } 36 | } 37 | 38 | const innerFuncs = outerFunction2() 39 | 40 | console.log(innerFuncs.plusOne) 41 | console.log(innerFuncs.minusOne) 42 | -------------------------------------------------------------------------------- /basics-i/day22/main3.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Document Object Model:30 Days Of JavaScript 6 | 7 | 8 | 9 |

Removing child Node

10 |

Asabeneh Yetayeh challenges in 2020

11 | 20 | 21 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /basics-i/day4/main.ts: -------------------------------------------------------------------------------- 1 | export { } 2 | 3 | let num = 3 4 | if (num > 0) { 5 | console.log(`${num} is a positive number`) 6 | } 7 | 8 | // If else 9 | num = 0 10 | if (num > 0) { 11 | console.log(`${num} is a positive number`) 12 | } else if (num < 0) { 13 | console.log(`${num} is a negative number`) 14 | } else { 15 | console.log(`${num} is zero`) 16 | } 17 | 18 | // Switch 19 | num = 0 20 | switch (true) { 21 | case num > 0: 22 | console.log(`${num} is positive`) 23 | break 24 | case num < 0: 25 | console.log(`${num} is negative`) 26 | break 27 | case num == 0: 28 | console.log(`${num} is zero`) 29 | break 30 | default: 31 | console.log(`${num} is not a number`) 32 | } 33 | 34 | let weather = 'cloudy' 35 | switch (weather) { 36 | case 'sunny': 37 | console.log('Bring some sunblock') 38 | break 39 | case 'rainy': 40 | console.log('Wear a rain coat.') 41 | break 42 | case 'snowy': 43 | console.log('Just stay at home') 44 | break 45 | default: 46 | console.log('Not sure what weather this is') 47 | break 48 | } 49 | 50 | // Ternary 51 | let isRaining = false 52 | isRaining 53 | ? console.log('Wear a rain coat.') 54 | : console.log('No need for a rain coat.') 55 | -------------------------------------------------------------------------------- /basics-i/day4/main.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | exports.__esModule = true; 3 | var num = 3; 4 | if (num > 0) { 5 | console.log(num + " is a positive number"); 6 | } 7 | // If else 8 | num = 0; 9 | if (num > 0) { 10 | console.log(num + " is a positive number"); 11 | } 12 | else if (num < 0) { 13 | console.log(num + " is a negative number"); 14 | } 15 | else { 16 | console.log(num + " is zero"); 17 | } 18 | // Switch 19 | num = 0; 20 | switch (true) { 21 | case num > 0: 22 | console.log(num + " is positive"); 23 | break; 24 | case num < 0: 25 | console.log(num + " is negative"); 26 | break; 27 | case num == 0: 28 | console.log(num + " is zero"); 29 | break; 30 | default: 31 | console.log(num + " is not a number"); 32 | } 33 | var weather = 'cloudy'; 34 | switch (weather) { 35 | case 'sunny': 36 | console.log('Bring some sunblock'); 37 | break; 38 | case 'rainy': 39 | console.log('Wear a rain coat.'); 40 | break; 41 | case 'snowy': 42 | console.log('Just stay at home'); 43 | break; 44 | default: 45 | console.log('Not sure what weather this is'); 46 | break; 47 | } 48 | // Ternary 49 | var isRaining = false; 50 | isRaining 51 | ? console.log('Wear a rain coat.') 52 | : console.log('No need for a rain coat.'); 53 | -------------------------------------------------------------------------------- /basics-i/day23/main.html: -------------------------------------------------------------------------------- 1 | 2 | 18 | 19 | 20 | 21 | 22 | Document Object Model 23 | 24 | 25 | 26 | 27 | 28 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /basics-i/day3/main.js: -------------------------------------------------------------------------------- 1 | // Increment operators (post increments are used more often) 2 | var count = 0; 3 | console.log(count++); // Post increment 4 | console.log(count++); // Post increment 5 | console.log(++count); // Pre increment 6 | console.log(++count); // Pre increment 7 | // Ternary operators 8 | var isRaining = true; 9 | isRaining 10 | ? console.log('You need a rain coat') 11 | : console.log('You DON\'T need a rain coat'); 12 | isRaining = false; 13 | console.log('It has stopped raining'); 14 | isRaining 15 | ? console.log('You need a rain coat') 16 | : console.log('You DON\'T need a rain coat'); 17 | var number = 5; 18 | number > 0 19 | ? console.log("Number " + number + " is positive") 20 | : console.log("Number " + number + " is negative"); 21 | number = -5; 22 | number > 0 23 | ? console.log("Number " + number + " is positive") 24 | : console.log("Number " + number + " is negative"); 25 | // Alerts, Prompts, and Confirms 26 | // SEE main.html 27 | /* What is the "new" keyword for? (the example below doesn't work without it) 28 | * From what I can infer, "new" is needed to create NON-NATIVE types 29 | * - https://stackoverflow.com/questions/39622778/what-is-new-in-typescript 30 | * - https://stackoverflow.com/a/38755779/3611239 31 | */ 32 | var now = new Date(); 33 | var allSeconds = Date.now(); 34 | console.log(now); 35 | console.log(now.getFullYear()); 36 | console.log(now.getMonth()); 37 | console.log(now.getHours()); 38 | console.log(now.getTime()); // Milliseconds since 1970-01-01 39 | console.log(allSeconds); 40 | console.log(now.getTime() == allSeconds); 41 | -------------------------------------------------------------------------------- /basics-i/day3/main.ts: -------------------------------------------------------------------------------- 1 | // Increment operators (post increments are used more often) 2 | let count = 0 3 | 4 | console.log(count++) // Post increment 5 | console.log(count++) // Post increment 6 | 7 | console.log(++count) // Pre increment 8 | console.log(++count) // Pre increment 9 | 10 | // Ternary operators 11 | let isRaining = true 12 | isRaining 13 | ? console.log('You need a rain coat') 14 | : console.log('You DON\'T need a rain coat') 15 | 16 | 17 | isRaining = false 18 | console.log('It has stopped raining') 19 | 20 | isRaining 21 | ? console.log('You need a rain coat') 22 | : console.log('You DON\'T need a rain coat') 23 | 24 | let number = 5 25 | number > 0 26 | ? console.log(`Number ${number} is positive`) 27 | : console.log(`Number ${number} is negative`) 28 | 29 | number = -5 30 | 31 | number > 0 32 | ? console.log(`Number ${number} is positive`) 33 | : console.log(`Number ${number} is negative`) 34 | 35 | 36 | // Alerts, Prompts, and Confirms 37 | // SEE main.html 38 | 39 | /* What is the "new" keyword for? (the example below doesn't work without it) 40 | * From what I can infer, "new" is needed to create NON-NATIVE types 41 | * - https://stackoverflow.com/questions/39622778/what-is-new-in-typescript 42 | * - https://stackoverflow.com/a/38755779/3611239 43 | */ 44 | const now = new Date() 45 | const allSeconds = Date.now() 46 | 47 | console.log(now) 48 | console.log(now.getFullYear()) 49 | console.log(now.getMonth()) 50 | console.log(now.getHours()) 51 | 52 | console.log(now.getTime()) // Milliseconds since 1970-01-01 53 | console.log(allSeconds) 54 | console.log(now.getTime() == allSeconds) 55 | 56 | 57 | -------------------------------------------------------------------------------- /basics-i/day14/main.ts: -------------------------------------------------------------------------------- 1 | export { } 2 | /* 3 | * try: wrap code that may throw an error in a try block 4 | * catch: write code to do something when an error occurs 5 | * - The catch block takes a parameter, and it's common to pass e, err, or error as parameter 6 | * finally: write code to always be executed regardless of error 7 | */ 8 | 9 | try { 10 | let lastName = 'Yan' 11 | let fullName = `${firstName} ${lastName}` 12 | console.log(fullName) 13 | } catch (e) { 14 | console.log(`Name of error: ${e.name}`) 15 | console.log(`Error message: ${e.message}`) 16 | } finally { 17 | console.log('This log will also be printed') 18 | } 19 | 20 | // Throw: allows us to create customer error 21 | // throw 'Custom error' 22 | // throw 42 23 | // throw true 24 | // throw new Error('This is a custom error') 25 | 26 | // Note: prompt() is not a valid construct in Node.js runtime, but it'll work in browser console 27 | // const throwErrorFunc = () => { 28 | // let message 29 | // let x = window.prompt('Enter a number: ') 30 | // try { 31 | // if (x == '') throw 'Empty input' 32 | // if (isNaN(x)) throw 'Not a number' 33 | // let numx = Number(x) 34 | // if (numx < 5) throw 'Number is too low' 35 | // if (numx > 10) throw 'Number is too high' 36 | // } catch (e) { 37 | // console.log(e) 38 | // } 39 | // } 40 | // throwErrorFunc() 41 | 42 | // Types of error 43 | let lastName = 'Yan' 44 | // let fullName = `${firstName} ${lastName}` 45 | // console.log(fullName) // ReferenceError as we try to use firstName that has not been declared 46 | 47 | let square = 2 x 2 // SyntaxError in JavaScript, but okay in TypeScript 48 | console.log(square) 49 | 50 | // Type error 51 | let num = 10 52 | console.log(num.toLowerCase()) // TypeError -------------------------------------------------------------------------------- /basics-i/day14/main.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | exports.__esModule = true; 3 | /* 4 | * try: wrap code that may throw an error in a try block 5 | * catch: write code to do something when an error occurs 6 | * - The catch block takes a parameter, and it's common to pass e, err, or error as parameter 7 | * finally: write code to always be executed regardless of error 8 | */ 9 | try { 10 | var lastName_1 = 'Yan'; 11 | var fullName = firstName + " " + lastName_1; 12 | console.log(fullName); 13 | } 14 | catch (e) { 15 | console.log("Name of error: " + e.name); 16 | console.log("Error message: " + e.message); 17 | } 18 | finally { 19 | console.log('This log will also be printed'); 20 | } 21 | // Throw: allows us to create customer error 22 | // throw 'Custom error' 23 | // throw 42 24 | // throw true 25 | // throw new Error('This is a custom error') 26 | // Note: prompt() is not a valid construct in Node.js runtime, but it'll work in browser console 27 | // const throwErrorFunc = () => { 28 | // let message 29 | // let x = window.prompt('Enter a number: ') 30 | // try { 31 | // if (x == '') throw 'Empty input' 32 | // if (isNaN(x)) throw 'Not a number' 33 | // let numx = Number(x) 34 | // if (numx < 5) throw 'Number is too low' 35 | // if (numx > 10) throw 'Number is too high' 36 | // } catch (e) { 37 | // console.log(e) 38 | // } 39 | // } 40 | // throwErrorFunc() 41 | // Types of error 42 | var lastName = 'Yan'; 43 | // let fullName = `${firstName} ${lastName}` 44 | // console.log(fullName) // ReferenceError as we try to use firstName that has not been declared 45 | var square = 2, x; 46 | 2; // SyntaxError in JavaScript, but okay in TypeScript 47 | console.log(square); 48 | // Type error 49 | var num = 10; 50 | console.log(num.toLowerCase()); // TypeError 51 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Learning TypeScript 2 | 3 | ## Context 4 | I work with data & machine learning, mostly running experiments, building 1-week prototypes & ML systems (>1k queries/sec, <140ms). I know Python, Scala, SQL, and basic HTML/CSS. 5 | 6 | To decide on what to learn in 2021, I ran two polls on [Twitter](https://twitter.com/eugeneyan/status/1343286184047300608) (400 votes) and [LinkedIn](https://www.linkedin.com/posts/eugeneyan_learning-programming-activity-6749056005809827840-0czR/) (200 votes). Based on the comments from friends in both polls, I decided that TypeScript (+ React) would be most fun and practical for me to pick up. 7 | 8 | ## Lesson plan (TypeScript) 9 | - [x] Overview: [TypeScript in 50 minutes](https://www.youtube.com/watch?v=WBPrJSw7yQA) 10 | - [ ] Basics I: [30 Days of JavaScript](https://github.com/Asabeneh/30-Days-Of-JavaScript) (We'll do this in TS) 11 | - [ ] Basics II: [JavaScript 30](https://javascript30.com) (We'll do this in TS too) 12 | 13 | ## Lesson plan (React) 14 | - [ ] [How to Learn React — A roadmap from beginner to advanced](https://www.freecodecamp.org/news/learning-react-roadmap-from-scratch-to-advanced-bff7735531b6/) 15 | - [ ] [Hands-on projects to learn the basics of React](https://hackernoon.com/hands-on-projects-to-learn-the-basics-of-react-3a06726514a8) 16 | - [ ] [8 React.js Project Ideas to Help You Start Learning by Doing](https://www.freecodecamp.org/news/8-reactjs-project-ideas-to-start-learning-by-doing/) 17 | 18 | ## Project 19 | - [ ] [SortMySkills](https://eugeneyan.com/writing/sortmyskills-is-now-live/) (Recreate this in TS instead of Ruby) 20 | 21 | 22 | ## Also recommended by others 23 | - [TypeScript Deep Dive](https://basarat.gitbook.io/typescript/) (perhaps after Basics II) 24 | - [Execute Program (TypeScript)](https://www.executeprogram.com/courses/typescript) (basic JS knowledge required) -------------------------------------------------------------------------------- /basics-i/day24/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Solar System: Document Object Model:30 Days Of JavaScript 6 | 7 | 8 | 9 | 23 | 24 | 25 |
26 |

Calculate a weight of an object on a planet

27 | 28 | 29 | 41 | 42 | 43 |
44 |
45 |
46 |
47 | 51 | 52 |
53 | 54 |
55 | 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /basics-i/day24/scripts/main.js: -------------------------------------------------------------------------------- 1 | var space = { 2 | earth: { 3 | gravity: 1.0, 4 | image: "earth.png" 5 | }, 6 | jupiter: { 7 | gravity: 2.34, 8 | image: "jupiter.png" 9 | }, 10 | mars: { 11 | gravity: 0.38, 12 | image: "mars.png" 13 | }, 14 | mercury: { 15 | gravity: 0.38, 16 | image: "mercury.png" 17 | }, 18 | moon: { 19 | gravity: 0.167, 20 | image: "moon.png" 21 | }, 22 | neptune: { 23 | gravity: 1.12, 24 | image: "neptune.png" 25 | }, 26 | pluto: { 27 | gravity: 0.067, 28 | image: "pluto.png" 29 | }, 30 | saturn: { 31 | gravity: 0.93, 32 | image: "saturn.png" 33 | }, 34 | uranus: { 35 | gravity: 0.93, 36 | image: "uranus.png" 37 | }, 38 | venus: { 39 | gravity: 0.91, 40 | image: "venus.png" 41 | } 42 | }; 43 | var input = document.querySelector("input"); 44 | var select = document.querySelector("select"); 45 | var button = document.querySelector("button"); 46 | var container = document.querySelector(".flex-container"); 47 | var weight; 48 | var containerUI = function (img, text) { 49 | var image = document.createElement("img"); 50 | image.src = "images/" + img; 51 | var p = document.createElement("p"); 52 | p.textContent = text + " N"; 53 | p.className = "big"; 54 | container; 55 | container.appendChild(image); 56 | container.appendChild(p); 57 | }; 58 | button.addEventListener("click", function () { 59 | var imgSrc; 60 | console.log("Select: " + select.value + ", Input: " + input.value); 61 | imgSrc = space[select.value].image; 62 | weight = Number(input.value) * space[select.value].gravity; 63 | containerUI(imgSrc, weight); 64 | console.log(weight); 65 | }); 66 | -------------------------------------------------------------------------------- /basics-i/day24/scripts/main.ts: -------------------------------------------------------------------------------- 1 | const space = { 2 | earth: { 3 | gravity: 1.0, 4 | image: "earth.png" 5 | }, 6 | jupiter: { 7 | gravity: 2.34, 8 | image: "jupiter.png" 9 | }, 10 | mars: { 11 | gravity: 0.38, 12 | image: "mars.png" 13 | }, 14 | mercury: { 15 | gravity: 0.38, 16 | image: "mercury.png" 17 | }, 18 | moon: { 19 | gravity: 0.167, 20 | image: "moon.png" 21 | }, 22 | neptune: { 23 | gravity: 1.12, 24 | image: "neptune.png" 25 | }, 26 | pluto: { 27 | gravity: 0.067, 28 | image: "pluto.png" 29 | }, 30 | saturn: { 31 | gravity: 0.93, 32 | image: "saturn.png" 33 | }, 34 | uranus: { 35 | gravity: 0.93, 36 | image: "uranus.png" 37 | }, 38 | venus: { 39 | gravity: 0.91, 40 | image: "venus.png" 41 | }, 42 | } 43 | 44 | const input = document.querySelector("input") 45 | const select = document.querySelector("select") 46 | const button = document.querySelector("button") 47 | const container = document.querySelector(".flex-container") 48 | let weight 49 | 50 | const containerUI = (img, text) => { 51 | let image = document.createElement("img") 52 | image.src = `images/${img}` 53 | let p = document.createElement("p") 54 | p.textContent = `${text} N` 55 | p.className = "big" 56 | container 57 | container.appendChild(image) 58 | container.appendChild(p) 59 | } 60 | 61 | button.addEventListener("click", function() { 62 | let imgSrc; 63 | 64 | console.log(`Select: ${select.value}, Input: ${input.value}`) 65 | imgSrc = space[select.value].image; 66 | weight = Number(input.value) * space[select.value].gravity; 67 | containerUI(imgSrc, weight); 68 | console.log(weight) 69 | }) -------------------------------------------------------------------------------- /basics-i/day7/main.ts: -------------------------------------------------------------------------------- 1 | function areaOfCircle(r: number) { 2 | let area: number = Math.PI * r * r 3 | return area 4 | } 5 | 6 | let r: number = 10 7 | console.log(`Area of circle with radius ${r}: ${areaOfCircle(r)}`) 8 | 9 | // Function with unlimited number of parameters 10 | // Unlimited params in regular function 11 | function printAllNums() { 12 | console.log(arguments) // [Arguments] { '0': 1, '1': 2, '2': 3, '3': 4 } 13 | } 14 | 15 | printAllNums(1, 2, 3, 4) // Even though VSCode complains, this works! 16 | 17 | function sumAllNums() { 18 | let sum = 0 19 | for (const arg of arguments) { 20 | sum += arg 21 | } 22 | return sum 23 | } 24 | 25 | console.log(sumAllNums(1, 2, 3, 4)) 26 | 27 | // Unlimited params in arrow function 28 | const printAllNums2 = (...args) => { 29 | console.log(args) // [ 1, 2, 3, 4 ] 30 | } 31 | 32 | printAllNums2(1, 2, 3, 4) 33 | 34 | const sumAllNums2 = (...args) => { 35 | let sum = 0 36 | for (const arg of args) { 37 | sum += arg 38 | } 39 | return sum 40 | } 41 | 42 | console.log(sumAllNums2(1, 2, 3, 4)) 43 | 44 | // Anonymous Function 45 | const anonymousFunc = function () { 46 | console.log('I\'m an anonymous function') 47 | } 48 | 49 | anonymousFunc() 50 | 51 | // Expression function 52 | const square = function (n) { 53 | return n * n 54 | } 55 | 56 | console.log(`Square of 10: ${square(10)}`) 57 | 58 | // Arrow functions 59 | const square2 = n => { 60 | return n * n 61 | } 62 | 63 | console.log(`Square of 7: ${square2(7)}`) 64 | 65 | // Function with default params 66 | function areaOfCircle2(r = 7) { 67 | return Math.PI * r * r 68 | } 69 | 70 | console.log(`Area of circle default is ${areaOfCircle2()}`) 71 | 72 | const areaOfCircle3 = (r = 8) => { 73 | return Math.PI * r * r 74 | } 75 | 76 | console.log(`Area of circle default is ${areaOfCircle3()}`) -------------------------------------------------------------------------------- /basics-i/day17/main.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Web Storage is a new HTML5 API offering that has benefits over traditional cookies. 3 | * Its limit is at least 5mb and is never transferred to the server. 4 | * The keys and values are alwasy strings (integer keys are converted to strings). 5 | * 6 | * There are two web storage objects: 7 | * - sessionStorage: data gets cleared when page session ends 8 | * - localStorage: simmilar to session storage, but no expiration date. Kept between browser sessions. 9 | */ 10 | // Needs installation first: "npm install node-localstorage" 11 | var LocalStorage = require('node-localstorage').LocalStorage; 12 | localStorage = new LocalStorage('./scratch'); 13 | localStorage.setItem('firstName', 'Eugene'); 14 | console.log(localStorage.getItem('firstName')); 15 | var skills = ['Python', 'Scala', 'TypeScript', 'SQL']; 16 | var skillsJSON = JSON.stringify(skills); 17 | localStorage.setItem('skills', skillsJSON); // Even though VSCode complains, this works fine 18 | console.log(localStorage.getItem('skills')); 19 | var userE = { 20 | firstName: 'Eugene', 21 | age: 25, 22 | skills: ['Python', 'Scala', 'TypeScript', 'SQL'] 23 | }; 24 | var userJSON = JSON.stringify(userE); 25 | localStorage.setItem('user', userJSON); 26 | console.log(localStorage.getItem('user')); 27 | console.log(JSON.parse(localStorage.getItem('user'))); // Parse the JSON 28 | console.log(localStorage.key); 29 | console.log(localStorage); 30 | // _keys: [ 'firstName', 'skills', 'user' ], 31 | // _metaKeyMap: Map <[Object: null prototype] {}> { 32 | // firstName: MetaKey { key: 'firstName', index: 0, size: 6 }, 33 | // skills: MetaKey { key: 'skills', index: 1, size: 37 }, 34 | // user: MetaKey { key: 'user', index: 2, size: 78 } 35 | // }, 36 | localStorage.clear(); 37 | console.log(localStorage); 38 | // _keys: [], 39 | // _metaKeyMap: Map <[Object: null prototype] {}> {}, 40 | -------------------------------------------------------------------------------- /basics-i/day2/main.js: -------------------------------------------------------------------------------- 1 | /* Primitive data types 2 | * - Cannot be modified once created 3 | */ 4 | var word = 'JavaScript'; 5 | // word[0] = 'Y' // Error 6 | /* Non-Primitimve Data Types 7 | * - Mutable 8 | * - Cannot be compared by value because they are reference types and thus compared by reference instead of value 9 | */ 10 | var nums = [1, 2, 3]; 11 | nums[0] = 10; 12 | console.log(nums); 13 | var nums2 = [1, 2, 3]; 14 | var nums3 = [1, 2, 3]; 15 | console.log(nums2 == nums3); // Returns false 16 | var pi = Math.PI; 17 | console.log(pi); 18 | console.log(Math.round(pi)); 19 | console.log(Math.round(9.5)); 20 | console.log(Math.floor(pi)); 21 | console.log(Math.ceil(pi)); 22 | console.log(Math.min(1, 3, 3, 4, 5)); 23 | console.log(Math.max(1, 3, 3, 4, 5)); 24 | var randNum = Math.random(); 25 | console.log(randNum); 26 | var firstName = 'Eugene'; 27 | var lastName = 'Yan'; 28 | var fullName = firstName + ' ' + lastName; 29 | console.log(fullName); 30 | console.log('Each \nword \nis \na \nnew \nline'); 31 | console.log('shouldn\'t, couldn\'t, wouldn\'t'); 32 | // String interpolation 33 | var a = 2; 34 | var b = 3; 35 | console.log("The sum of " + a + " and " + b + " is " + (a + b)); 36 | // String methdods 37 | console.log(firstName.length); 38 | console.log(firstName[0]); 39 | console.log(firstName[firstName.length - 1]); 40 | console.log(firstName.substr(1, 3)); 41 | console.log(firstName.substring(1, 3)); // Doesn't include char at end index 42 | // Splitting strings 43 | var sentence = 'This is a sentence'; 44 | console.log(sentence.split(' ')); 45 | console.log(sentence.split(' ')[0]); 46 | // Checking types 47 | console.log(typeof 'Eugene'); 48 | console.log(typeof 8); 49 | console.log(typeof Math.PI); 50 | console.log(typeof true); 51 | // Casting 52 | var num = '10'; 53 | var numInt = parseInt(num); 54 | console.log(num + " (" + typeof num + "), " + numInt + " (" + typeof numInt + ")"); 55 | -------------------------------------------------------------------------------- /basics-i/day17/main.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Web Storage is a new HTML5 API offering that has benefits over traditional cookies. 3 | * Its limit is at least 5mb and is never transferred to the server. 4 | * The keys and values are alwasy strings (integer keys are converted to strings). 5 | * 6 | * There are two web storage objects: 7 | * - sessionStorage: data gets cleared when page session ends 8 | * - localStorage: simmilar to session storage, but no expiration date. Kept between browser sessions. 9 | */ 10 | // Needs installation first: "npm install node-localstorage" 11 | var LocalStorage = require('node-localstorage').LocalStorage 12 | localStorage = new LocalStorage('./scratch') 13 | 14 | localStorage.setItem('firstName', 'Eugene') 15 | console.log(localStorage.getItem('firstName')) 16 | 17 | const skills = ['Python', 'Scala', 'TypeScript', 'SQL'] 18 | const skillsJSON = JSON.stringify(skills) 19 | localStorage.setItem('skills', skillsJSON) // Even though VSCode complains, this works fine 20 | console.log(localStorage.getItem('skills')) 21 | 22 | const userE = { 23 | firstName: 'Eugene', 24 | age: 25, 25 | skills: ['Python', 'Scala', 'TypeScript', 'SQL'] 26 | } 27 | const userJSON = JSON.stringify(userE) 28 | localStorage.setItem('user', userJSON) 29 | console.log(localStorage.getItem('user')) 30 | console.log(JSON.parse(localStorage.getItem('user'))) // Parse the JSON 31 | 32 | console.log(localStorage.key) 33 | console.log(localStorage) 34 | // _keys: [ 'firstName', 'skills', 'user' ], 35 | // _metaKeyMap: Map <[Object: null prototype] {}> { 36 | // firstName: MetaKey { key: 'firstName', index: 0, size: 6 }, 37 | // skills: MetaKey { key: 'skills', index: 1, size: 37 }, 38 | // user: MetaKey { key: 'user', index: 2, size: 78 } 39 | // }, 40 | 41 | localStorage.clear() 42 | console.log(localStorage) 43 | // _keys: [], 44 | // _metaKeyMap: Map <[Object: null prototype] {}> {}, -------------------------------------------------------------------------------- /basics-i/day2/main.ts: -------------------------------------------------------------------------------- 1 | /* Primitive data types 2 | * - Cannot be modified once created 3 | */ 4 | 5 | let word = 'JavaScript' 6 | // word[0] = 'Y' // Error 7 | 8 | /* Non-Primitimve Data Types 9 | * - Mutable 10 | * - Cannot be compared by value because they are reference types and thus compared by reference instead of value 11 | */ 12 | 13 | let nums = [1, 2, 3] 14 | nums[0] = 10 15 | 16 | console.log(nums) 17 | 18 | let nums2 = [1, 2, 3] 19 | let nums3 = [1, 2, 3] 20 | 21 | console.log(nums2 == nums3) // Returns false 22 | 23 | const pi = Math.PI 24 | 25 | console.log(pi) 26 | console.log(Math.round(pi)) 27 | console.log(Math.round(9.5)) 28 | console.log(Math.floor(pi)) 29 | console.log(Math.ceil(pi)) 30 | console.log(Math.min(1, 3, 3, 4, 5)) 31 | console.log(Math.max(1, 3, 3, 4, 5)) 32 | 33 | let randNum = Math.random() 34 | console.log(randNum) 35 | 36 | let firstName = 'Eugene' 37 | let lastName = 'Yan' 38 | 39 | let fullName = firstName + ' ' + lastName 40 | console.log(fullName) 41 | 42 | console.log('Each \nword \nis \na \nnew \nline') 43 | console.log('shouldn\'t, couldn\'t, wouldn\'t') 44 | 45 | // String interpolation 46 | let a = 2 47 | let b = 3 48 | console.log(`The sum of ${a} and ${b} is ${a + b}`) 49 | 50 | // String methdods 51 | console.log(firstName.length) 52 | console.log(firstName[0]) 53 | console.log(firstName[firstName.length - 1]) 54 | 55 | console.log(firstName.substr(1, 3)) 56 | console.log(firstName.substring(1, 3)) // Doesn't include char at end index 57 | 58 | // Splitting strings 59 | let sentence = 'This is a sentence' 60 | console.log(sentence.split(' ')) 61 | console.log(sentence.split(' ')[0]) 62 | 63 | // Checking types 64 | console.log(typeof 'Eugene') 65 | console.log(typeof 8) 66 | console.log(typeof Math.PI) 67 | console.log(typeof true) 68 | 69 | // Casting 70 | let num: string = '10' 71 | let numInt: number = parseInt(num) 72 | console.log(`${num} (${typeof num}), ${numInt} (${typeof numInt})`) 73 | -------------------------------------------------------------------------------- /basics-i/day21/main.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | exports.__esModule = true; 3 | /* 4 | * We can get, create, append, or remove HTML elements using JavaScript 5 | * Selecting HTML elements via JavaScript is similar to selecting using CSS 6 | * To select a HTML elemnt, we use tag name, id, class name, or other attributes 7 | */ 8 | var allTitles = document.getElementsByTagName('h1'); 9 | console.log(allTitles); 10 | console.log(allTitles.length); 11 | for (var i = 0; i < allTitles.length; i++) { 12 | console.log(allTitles[i]); 13 | } 14 | // Right-click on main.html and start live server. 15 | // Then, copy-paste the compiled main.js into console. 16 | var allTitles2 = document.getElementsByClassName('title'); 17 | console.log(allTitles2); 18 | console.log(allTitles2.length); 19 | for (var i = 0; i < allTitles2.length; i++) { 20 | console.log(allTitles2[i]); 21 | } 22 | var firstTitle = document.getElementById('first-title'); 23 | console.log(firstTitle); 24 | // querySelector() can select HTML element by tag name, id, or class name. 25 | // It only returns the first element 26 | var firstTitle2 = document.querySelector('h1'); 27 | var firstTitle3 = document.querySelector('#first-title'); 28 | var firstTitle4 = document.querySelector('.title'); 29 | console.log(firstTitle2, firstTitle3, firstTitle4); 30 | // querySelectorAll() used to select html element by tag name or class 31 | var allTitles3 = document.querySelectorAll('h1'); 32 | console.log(allTitles3.length); // 4 33 | for (var i = 0; i < allTitles3.length; i++) { 34 | console.log(allTitles3[i]); 35 | } 36 | // Adding attributes 37 | var titles = document.querySelectorAll('h1'); 38 | titles[3].className = 'title'; 39 | titles[3].id = 'forth-title'; 40 | titles[3].textContent = 'Forth Title'; // Needs textContent to show up 41 | // titles[3].setAttribute('class', 'title') 42 | // titles[3].setAttribute('id', 'fourth-title') 43 | // Add style 44 | console.log(titles); 45 | titles.forEach(function (title, i) { 46 | title.style.fontSize = '24px'; 47 | if (i % 2 === 0) { 48 | title.style.color = 'green'; 49 | } 50 | else { 51 | title.style.color = 'red'; 52 | } 53 | }); 54 | -------------------------------------------------------------------------------- /basics-i/day21/main.ts: -------------------------------------------------------------------------------- 1 | import { title } from "node:process" 2 | 3 | /* 4 | * We can get, create, append, or remove HTML elements using JavaScript 5 | * Selecting HTML elements via JavaScript is similar to selecting using CSS 6 | * To select a HTML elemnt, we use tag name, id, class name, or other attributes 7 | */ 8 | const allTitles = document.getElementsByTagName('h1') 9 | console.log(allTitles) 10 | console.log(allTitles.length) 11 | 12 | for (let i = 0; i < allTitles.length; i++) { 13 | console.log(allTitles[i]) 14 | } 15 | 16 | // Right-click on main.html and start live server. 17 | // Then, copy-paste the compiled main.js into console. 18 | 19 | const allTitles2 = document.getElementsByClassName('title') 20 | console.log(allTitles2) 21 | console.log(allTitles2.length) 22 | 23 | for (let i = 0; i < allTitles2.length; i++) { 24 | console.log(allTitles2[i]) 25 | } 26 | 27 | let firstTitle = document.getElementById('first-title') 28 | console.log(firstTitle) 29 | 30 | // querySelector() can select HTML element by tag name, id, or class name. 31 | // It only returns the first element 32 | let firstTitle2 = document.querySelector('h1') 33 | let firstTitle3 = document.querySelector('#first-title') 34 | let firstTitle4 = document.querySelector('.title') 35 | 36 | console.log(firstTitle2, firstTitle3, firstTitle4) 37 | 38 | // querySelectorAll() used to select html element by tag name or class 39 | const allTitles3 = document.querySelectorAll('h1') 40 | 41 | console.log(allTitles3.length) // 4 42 | for (let i = 0; i < allTitles3.length; i++) { 43 | console.log(allTitles3[i]) 44 | } 45 | 46 | // Adding attributes 47 | const titles = document.querySelectorAll('h1') 48 | titles[3].className = 'title' 49 | titles[3].id = 'forth-title' 50 | titles[3].textContent = 'Forth Title' // Needs textContent to show up 51 | 52 | // titles[3].setAttribute('class', 'title') 53 | // titles[3].setAttribute('id', 'fourth-title') 54 | 55 | // Add style 56 | console.log(titles) 57 | titles.forEach((title, i) => { 58 | title.style.fontSize = '24px' 59 | if (i % 2 === 0) { 60 | title.style.color = 'green' 61 | } else { 62 | title.style.color = 'red' 63 | } 64 | }) -------------------------------------------------------------------------------- /basics-i/day7/main.js: -------------------------------------------------------------------------------- 1 | function areaOfCircle(r) { 2 | var area = Math.PI * r * r; 3 | return area; 4 | } 5 | var r = 10; 6 | console.log("Area of circle with radius " + r + ": " + areaOfCircle(r)); 7 | // Function with unlimited number of parameters 8 | // Unlimited params in regular function 9 | function printAllNums() { 10 | console.log(arguments); // [Arguments] { '0': 1, '1': 2, '2': 3, '3': 4 } 11 | } 12 | printAllNums(1, 2, 3, 4); // Even though VSCode complains, this works! 13 | function sumAllNums() { 14 | var sum = 0; 15 | for (var _i = 0, arguments_1 = arguments; _i < arguments_1.length; _i++) { 16 | var arg = arguments_1[_i]; 17 | sum += arg; 18 | } 19 | return sum; 20 | } 21 | console.log(sumAllNums(1, 2, 3, 4)); 22 | // Unlimited params in arrow function 23 | var printAllNums2 = function () { 24 | var args = []; 25 | for (var _i = 0; _i < arguments.length; _i++) { 26 | args[_i] = arguments[_i]; 27 | } 28 | console.log(args); // [ 1, 2, 3, 4 ] 29 | }; 30 | printAllNums2(1, 2, 3, 4); 31 | var sumAllNums2 = function () { 32 | var args = []; 33 | for (var _i = 0; _i < arguments.length; _i++) { 34 | args[_i] = arguments[_i]; 35 | } 36 | var sum = 0; 37 | for (var _a = 0, args_1 = args; _a < args_1.length; _a++) { 38 | var arg = args_1[_a]; 39 | sum += arg; 40 | } 41 | return sum; 42 | }; 43 | console.log(sumAllNums2(1, 2, 3, 4)); 44 | // Anonymous Function 45 | var anonymousFunc = function () { 46 | console.log('I\'m an anonymous function'); 47 | }; 48 | anonymousFunc(); 49 | // Expression function 50 | var square = function (n) { 51 | return n * n; 52 | }; 53 | console.log("Square of 10: " + square(10)); 54 | // Arrow functions 55 | var square2 = function (n) { 56 | return n * n; 57 | }; 58 | console.log("Square of 7: " + square2(7)); 59 | // Function with default params 60 | function areaOfCircle2(r) { 61 | if (r === void 0) { r = 7; } 62 | return Math.PI * r * r; 63 | } 64 | console.log("Area of circle default is " + areaOfCircle2()); 65 | var areaOfCircle3 = function (r) { 66 | if (r === void 0) { r = 8; } 67 | return Math.PI * r * r; 68 | }; 69 | console.log("Area of circle default is " + areaOfCircle3()); 70 | -------------------------------------------------------------------------------- /basics-i/day5/main.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | exports.__esModule = true; 3 | // Arrays 4 | var nums = [0, 1, 2, 3, 5, 6]; 5 | console.log('Numbers: ', nums); 6 | console.log("Numbers: " + nums + " (Length: " + nums.length + ")"); 7 | // Splitting arrays 8 | var faang = ('Facebook Amazon Apple Netflix Google'); 9 | var faangArray = faang.split(' '); 10 | console.log('FAANG: ', faangArray); 11 | console.log("FAANG: " + faangArray); 12 | // Constructing an empty array 13 | var emptyArray = Array(8); 14 | console.log(emptyArray); 15 | emptyArray[0] = '1'; 16 | emptyArray[5] = 6; 17 | console.log(emptyArray); 18 | emptyArray.fill(0); 19 | console.log(emptyArray); 20 | var array1 = [0, 1, 2]; 21 | var array2 = [3, 4, 5]; 22 | var arrayCombined = array1.concat(array2); 23 | console.log(arrayCombined); 24 | // Check if item in array 25 | var coy = 'Snap'; 26 | var index = faangArray.indexOf(coy); 27 | if (index != -1) { 28 | console.log(coy + " is in FAANG"); 29 | } 30 | else { 31 | console.log(coy + " is not in FAANG"); 32 | } 33 | if (faangArray.includes(coy)) { 34 | console.log(coy + " is in FAANG"); 35 | } 36 | else { 37 | console.log(coy + " is not in FAANG"); 38 | } 39 | console.log(faangArray.toString()); 40 | console.log(faangArray.join(', ')); 41 | // Sliceing arrayw 42 | console.log(nums.slice()); 43 | console.log(nums.slice(1, 4)); 44 | // Push and pop 45 | faangArray.push('Stripe'); // Add item to the end 46 | console.log(faangArray); 47 | faangArray.pop(); // Remove item from the end 48 | console.log(faangArray); 49 | faangArray.unshift('Stripe'); // Add item at the start 50 | console.log(faangArray); 51 | faangArray.reverse(); 52 | console.log(faangArray); 53 | // Exercise Level 3 54 | var ages = [19, 22, 19, 24, 20, 25, 26, 24, 25, 24]; 55 | ages.sort(); 56 | var minAge = ages[0]; 57 | var maxAge = ages[ages.length - 1]; 58 | console.log("Min age: " + minAge + ", Max age: " + maxAge); 59 | function getMedian(array) { 60 | var midIndex = Math.floor(array.length / 2); 61 | if (array.length % 2 === 0) { 62 | return array[midIndex]; 63 | } 64 | else { 65 | return (array[midIndex - 1] + array[midIndex]) / 2; 66 | } 67 | } 68 | console.log("Median age: " + getMedian(ages)); 69 | var sum = ages.reduce(function (a, b) { return a + b; }, 0); 70 | var mean = sum / ages.length; 71 | console.log("Mean age: " + mean); 72 | console.log("Range of ages: " + maxAge + " - " + minAge + " = " + (maxAge - minAge)); 73 | -------------------------------------------------------------------------------- /basics-i/day5/main.ts: -------------------------------------------------------------------------------- 1 | export { } 2 | 3 | // Arrays 4 | const nums = [0, 1, 2, 3, 5, 6] 5 | console.log('Numbers: ', nums) 6 | console.log(`Numbers: ${nums} (Length: ${nums.length})`) 7 | 8 | // Splitting arrays 9 | const faang = ('Facebook Amazon Apple Netflix Google') 10 | const faangArray = faang.split(' ') 11 | console.log('FAANG: ', faangArray) 12 | console.log(`FAANG: ${faangArray}`) 13 | 14 | // Constructing an empty array 15 | const emptyArray = Array(8) 16 | console.log(emptyArray) 17 | 18 | emptyArray[0] = '1' 19 | emptyArray[5] = 6 20 | console.log(emptyArray) 21 | 22 | emptyArray.fill(0) 23 | console.log(emptyArray) 24 | 25 | let array1 = [0, 1, 2] 26 | let array2 = [3, 4, 5] 27 | let arrayCombined = array1.concat(array2) 28 | 29 | console.log(arrayCombined) 30 | 31 | // Check if item in array 32 | let coy = 'Snap' 33 | let index = faangArray.indexOf(coy) 34 | 35 | if (index != -1) { 36 | console.log(`${coy} is in FAANG`) 37 | } else { 38 | console.log(`${coy} is not in FAANG`) 39 | } 40 | 41 | if (faangArray.includes(coy)) { 42 | console.log(`${coy} is in FAANG`) 43 | } else { 44 | console.log(`${coy} is not in FAANG`) 45 | } 46 | 47 | console.log(faangArray.toString()) 48 | console.log(faangArray.join(', ')) 49 | 50 | // Sliceing arrayw 51 | console.log(nums.slice()) 52 | console.log(nums.slice(1, 4)) 53 | 54 | // Push and pop 55 | faangArray.push('Stripe') // Add item to the end 56 | console.log(faangArray) 57 | 58 | faangArray.pop() // Remove item from the end 59 | console.log(faangArray) 60 | 61 | faangArray.unshift('Stripe') // Add item at the start 62 | console.log(faangArray) 63 | 64 | faangArray.reverse() 65 | console.log(faangArray) 66 | 67 | // Exercise Level 3 68 | const ages = [19, 22, 19, 24, 20, 25, 26, 24, 25, 24] 69 | 70 | ages.sort() 71 | let minAge = ages[0] 72 | let maxAge = ages[ages.length - 1] 73 | console.log(`Min age: ${minAge}, Max age: ${maxAge}`) 74 | 75 | function getMedian(array: Array) { 76 | let midIndex = Math.floor(array.length / 2) 77 | 78 | if (array.length % 2 === 0) { 79 | return array[midIndex] 80 | } else { 81 | return (array[midIndex - 1] + array[midIndex]) / 2 82 | } 83 | } 84 | 85 | console.log(`Median age: ${getMedian(ages)}`) 86 | 87 | let sum = ages.reduce((a, b) => a + b, 0) 88 | let mean = sum / ages.length 89 | 90 | console.log(`Mean age: ${mean}`) 91 | 92 | console.log(`Range of ages: ${maxAge} - ${minAge} = ${maxAge - minAge}`) -------------------------------------------------------------------------------- /basics-i/day10/main.ts: -------------------------------------------------------------------------------- 1 | export { } 2 | 3 | // Create empty set 4 | const companies = new Set() 5 | console.log(companies) 6 | 7 | // Create set from array 8 | const languages = [ 9 | 'English', 10 | 'Finnish', 11 | 'English', 12 | 'French', 13 | 'Spanish', 14 | 'English', 15 | 'French', 16 | ] 17 | 18 | 19 | const setOfLanguages = new Set(languages) 20 | console.log(setOfLanguages) 21 | 22 | // We can iterate through sets 23 | for (const language of setOfLanguages) { 24 | console.log(language) 25 | } 26 | 27 | // Adding elements to set 28 | console.log(companies.size) 29 | 30 | companies.add('Facebook') 31 | companies.add('Amazon') 32 | companies.add('Apple') 33 | companies.add('Netflix') 34 | companies.add('Google') 35 | 36 | console.log(companies.size) 37 | console.log(companies) 38 | 39 | // Deleting an element from a set 40 | companies.delete('Google') 41 | console.log(companies.size) 42 | console.log(companies) 43 | 44 | // Checking if in element 45 | console.log(companies.has('Apple')) 46 | console.log(companies.has('Snapchat')) 47 | 48 | // Clearing the set 49 | companies.clear() 50 | console.log(companies) 51 | 52 | // Union of sets 53 | let a = [1, 2, 3, 4, 5] 54 | let b = [3, 4, 5, 6] 55 | let c = [...a, ...b] 56 | 57 | let A = new Set(a) 58 | let B = new Set(b) 59 | let C = new Set(c) 60 | 61 | console.log(C) 62 | 63 | // Intersection of sets 64 | let cIntersect = a.filter((num) => B.has(num)) 65 | console.log(cIntersect) 66 | 67 | // Difference of sets 68 | let cDiff = a.filter((num) => !B.has(num)) 69 | console.log(cDiff) 70 | 71 | // Creating an empty Map 72 | const map = new Map() 73 | console.log(map) 74 | 75 | // Creating a Map from array 76 | const countries = [ 77 | ['Finland', 'Helsinki'], 78 | ['Sweden', 'Stockholm'], 79 | ['Norway', 'Oslo'], 80 | ] 81 | 82 | const mapCountries: Map = new Map (countries) 83 | console.log(mapCountries.size) 84 | console.log(mapCountries) 85 | 86 | // Adding values to map 87 | const countriesMap = new Map() 88 | console.log(countriesMap.size) 89 | 90 | countriesMap.set('Finland', 'Helsinki') 91 | countriesMap.set('Sweden', 'Stockholm') 92 | countriesMap.set('Norway', 'Oslo') 93 | 94 | console.log(countriesMap.size) 95 | console.log(countriesMap) 96 | 97 | // Getting value from Map 98 | console.log(countriesMap.get('Finland')) 99 | 100 | // Checking key in Map 101 | console.log(countriesMap.has('Finland')) 102 | 103 | // Get all values from Map via loop 104 | for (const country of countriesMap) { 105 | console.log(country) 106 | } -------------------------------------------------------------------------------- /basics-i/day6/main.ts: -------------------------------------------------------------------------------- 1 | // For loop 2 | for (let i = 0; i <= 5; i++) { 3 | console.log(`${i} * ${i} = ${i * i}`) 4 | } 5 | 6 | const cities = ['Singapore', 'Seattle', 'San Francisco', 'Shanghai', 'Seoul'] 7 | const citiesUpper = [] 8 | 9 | for (let i = 0; i < cities.length; i++) { 10 | citiesUpper.push(cities[i].toUpperCase()) 11 | } 12 | 13 | console.log(`Cities: ${cities}`) 14 | console.log(`CITIES: ${citiesUpper}`) 15 | 16 | // While loop 17 | let i = 0 18 | while (i <= 5) { 19 | console.log(i) 20 | i++ 21 | } 22 | 23 | // Iterating through arrays 24 | const citiesLower = [] 25 | for (const city of cities) { 26 | citiesLower.push(city.toLowerCase()) 27 | } 28 | 29 | console.log(`Cities: ${cities}`) 30 | console.log(`cities: ${citiesLower}`) 31 | 32 | // Break 33 | for (let i = 0; i <= 5; i++) { 34 | console.log(i) 35 | if (i >= 3) { 36 | break // Break once we reach 3 37 | } 38 | } 39 | 40 | // Continue 41 | for (let i = 0; i <= 5; i++) { 42 | if (i == 3) { 43 | continue // Skip number 3 44 | } 45 | console.log(i) 46 | } 47 | 48 | /* 49 | * Find the country containing the hightest number of characters in the countries array 50 | * Extract all the countries contain the word 'land' from the countries array and print it as array 51 | * Extract all the countries containing only four characters from the countries array and print it as array 52 | *Extract all the countries containing two or more words from the countries array and print it as array 53 | * Reverse the countries array and capitalize each country and stored it as an array 54 | */ 55 | 56 | const countries = ['Albania', 'Bolivia', 'Canada', 'Denmark', 'Ethiopia', 'Finland', 'Germany', 57 | 'Hungary', 'Ireland', 'Japan', 'Kenya', 'Libya'] 58 | 59 | let highestCharCount = 0 60 | let highestCharCountCountry = null 61 | 62 | for (const country of countries) { // Note: This should be of, not in 63 | let charCount = country.length 64 | // console.log(`${country} (${charCount})`) 65 | if (charCount > highestCharCount) { 66 | highestCharCount = charCount 67 | highestCharCountCountry = country 68 | } 69 | } 70 | 71 | console.log(`The country with the highest char count is: ${highestCharCountCountry} (${highestCharCount})`) 72 | 73 | let countriesWithLand = [] 74 | 75 | for (const country of countries) { 76 | if (country.includes('land')) { 77 | countriesWithLand.push(country) 78 | } 79 | } 80 | 81 | console.log(`Countries with land: ${countriesWithLand}`) 82 | 83 | let countriesReversed = [] 84 | 85 | for (let i = countries.length - 1; i >= 0; i--) { 86 | countriesReversed.push(countries[i].toUpperCase()) 87 | } 88 | 89 | console.log(`Countries reversed and uppercased: ${countriesReversed}`) -------------------------------------------------------------------------------- /basics-i/day6/main.js: -------------------------------------------------------------------------------- 1 | // For loop 2 | for (var i_1 = 0; i_1 <= 5; i_1++) { 3 | console.log(i_1 + " * " + i_1 + " = " + i_1 * i_1); 4 | } 5 | var cities = ['Singapore', 'Seattle', 'San Francisco', 'Shanghai', 'Seoul']; 6 | var citiesUpper = []; 7 | for (var i_2 = 0; i_2 < cities.length; i_2++) { 8 | citiesUpper.push(cities[i_2].toUpperCase()); 9 | } 10 | console.log("Cities: " + cities); 11 | console.log("CITIES: " + citiesUpper); 12 | // While loop 13 | var i = 0; 14 | while (i <= 5) { 15 | console.log(i); 16 | i++; 17 | } 18 | // Iterating through arrays 19 | var citiesLower = []; 20 | for (var _i = 0, cities_1 = cities; _i < cities_1.length; _i++) { 21 | var city = cities_1[_i]; 22 | citiesLower.push(city.toLowerCase()); 23 | } 24 | console.log("Cities: " + cities); 25 | console.log("cities: " + citiesLower); 26 | // Break 27 | for (var i_3 = 0; i_3 <= 5; i_3++) { 28 | console.log(i_3); 29 | if (i_3 >= 3) { 30 | break; // Break once we reach 3 31 | } 32 | } 33 | // Continue 34 | for (var i_4 = 0; i_4 <= 5; i_4++) { 35 | if (i_4 == 3) { 36 | continue; // Skip number 3 37 | } 38 | console.log(i_4); 39 | } 40 | /* 41 | * Find the country containing the hightest number of characters in the countries array 42 | * Extract all the countries contain the word 'land' from the countries array and print it as array 43 | * Extract all the countries containing only four characters from the countries array and print it as array 44 | *Extract all the countries containing two or more words from the countries array and print it as array 45 | * Reverse the countries array and capitalize each country and stored it as an array 46 | */ 47 | var countries = ['Albania', 'Bolivia', 'Canada', 'Denmark', 'Ethiopia', 'Finland', 'Germany', 48 | 'Hungary', 'Ireland', 'Japan', 'Kenya', 'Libya']; 49 | var highestCharCount = 0; 50 | var highestCharCountCountry = null; 51 | for (var _a = 0, countries_1 = countries; _a < countries_1.length; _a++) { // Note: This should be of, not in 52 | var country = countries_1[_a]; 53 | var charCount = country.length; 54 | // console.log(`${country} (${charCount})`) 55 | if (charCount > highestCharCount) { 56 | highestCharCount = charCount; 57 | highestCharCountCountry = country; 58 | } 59 | } 60 | console.log("The country with the highest char count is: " + highestCharCountCountry + " (" + highestCharCount + ")"); 61 | var countriesWithLand = []; 62 | for (var _b = 0, countries_2 = countries; _b < countries_2.length; _b++) { 63 | var country = countries_2[_b]; 64 | if (country.includes('land')) { 65 | countriesWithLand.push(country); 66 | } 67 | } 68 | console.log("Countries with land: " + countriesWithLand); 69 | var countriesReversed = []; 70 | for (var i_5 = countries.length - 1; i_5 >= 0; i_5--) { 71 | countriesReversed.push(countries[i_5].toUpperCase()); 72 | } 73 | console.log("Countries reversed and uppercased: " + countriesReversed); 74 | -------------------------------------------------------------------------------- /overview/main.ts: -------------------------------------------------------------------------------- 1 | // Based on https://www.youtube.com/watch?v=WBPrJSw7yQA 2 | export { } 3 | let message = 'Welcome back!'; 4 | console.log(message); 5 | 6 | let x = 10; 7 | const y = 20; 8 | 9 | let sum; 10 | const title = 'Codevolution'; 11 | 12 | let isBeginner: boolean = true; 13 | let total: number = 0; 14 | let name: string = 'Eugene'; 15 | 16 | let sentence: string = `My name is ${name} 17 | I'm a beginner in Typescript`; 18 | 19 | console.log(sentence); 20 | 21 | let n: null = null; 22 | let u: undefined = undefined; 23 | 24 | let isNew: boolean = null; 25 | let myName: string = undefined; 26 | 27 | let list1: number[] = [1, 2, 3]; 28 | let list2: Array = [1, 2, 3]; 29 | 30 | let person1: [string, number] = ['Eugene', 34]; 31 | 32 | enum Color { Red = 5, Green, Blue }; 33 | 34 | let c: Color = Color.Green; 35 | console.log(c); 36 | 37 | let randomValue: any = 10; 38 | randomValue = 'Eugene'; 39 | 40 | let myVariable: unknown = 10; 41 | 42 | // (myVariable as string).toUpperCase(); // This only casts the number as a string, but does not change the type of myVariable 43 | // Thus, it is still treated as a number and when we try to call toUpperCase() on it, we get an error. 44 | 45 | // Solve it by converting the number to a string first, then calling toUpperCase() on it. 46 | let aString: string = String(myVariable); 47 | console.log(aString.toUpperCase()); 48 | 49 | function hasName(obj: any): obj is { name: string } { 50 | return !!obj && 51 | typeof obj === 'object' && 52 | 'name' in obj 53 | } 54 | 55 | if (hasName(myVariable)) { 56 | console.log(myVariable.name); 57 | } 58 | 59 | let a; 60 | a = 10; 61 | 62 | let b = 20; // Type inference 63 | // b = true; // Type error 64 | 65 | let multiType: number | boolean; 66 | multiType = 20; 67 | multiType = true; 68 | 69 | function add(num1: number, num2?: number): number { 70 | if (num2) 71 | return num1 + num2; 72 | else 73 | return num1; 74 | } 75 | 76 | let z: number = add(10, 20); 77 | console.log(`z = ${z}`) 78 | let d: number = add(10); 79 | console.log(`d = ${d}`) 80 | 81 | interface Person { 82 | firstName: string; 83 | lastName?: string; // Optional parameter 84 | } 85 | 86 | function fullName(person: Person) { 87 | console.log(`${person.firstName} ${person.lastName}`); 88 | } 89 | 90 | let p = { 91 | firstName: 'Bruce' 92 | } 93 | 94 | fullName(p) 95 | 96 | class Employee { 97 | public employeeName: string; 98 | 99 | constructor(name: string) { 100 | this.employeeName = name; 101 | } 102 | 103 | greet() { 104 | console.log(`Good Morning ${this.employeeName}`); 105 | } 106 | } 107 | 108 | let e1 = new Employee('Eugene'); 109 | console.log(e1.employeeName); 110 | e1.greet(); 111 | 112 | class Manager extends Employee { 113 | constructor(managerName: string) { 114 | super(managerName); 115 | } 116 | 117 | delegateWork() { 118 | console.log(`Manager ${this.employeeName} delegating work`); 119 | } 120 | } 121 | 122 | let m1 = new Manager('Xinyi'); 123 | m1.delegateWork(); 124 | m1.greet(); 125 | console.log(m1.employeeName); 126 | 127 | -------------------------------------------------------------------------------- /basics-i/day11/main.ts: -------------------------------------------------------------------------------- 1 | export { } 2 | 3 | // Destructing is a way to unpack arrays and assign them to a distinct variable 4 | const numbers = [1, 2, 3] 5 | let [one, two, three] = numbers 6 | 7 | console.log(one, two, three) 8 | 9 | // To sip values on values in the array just use an additional comma 10 | let [numOne, , numThree] = numbers 11 | console.log(numOne, numThree) 12 | 13 | const names = [undefined, 'A', 'B'] 14 | 15 | let [first = 'First', 16 | second, 17 | third, 18 | forth = 'Forth'] = names 19 | console.log(first, second, third, forth) 20 | 21 | // We can use the spread operator (...) to assign the remaining 22 | const nums = [1, 2, 3, 4, 5, 6, 7, 8] 23 | let [num1, num2, num3, ...rest] = nums 24 | 25 | console.log(num1, num2, num3) 26 | console.log(rest) 27 | 28 | // We can also destructure via iteration 29 | const countries = [['Finland', 'Helsinki'], ['Sweden', 'Stockholm'], ['Norway', 'Oslo']] 30 | 31 | for (const [country, city] of countries) { 32 | console.log(country, city) 33 | } 34 | 35 | // When destructuring objects, the name of variable should be exactly the same as object keys 36 | // Destructuring is done using { } 37 | const rect = { 38 | width: 20, 39 | height: 10, 40 | area: 200 41 | } 42 | let { width, height, area, perimeter } = rect 43 | console.log(width, height, area, perimeter) // perimeter will be undefined 44 | 45 | // You can also rename when restructuring 46 | let { width: w, height: h, area: a, perimeter: p } = rect 47 | console.log(w, h, a, p) 48 | 49 | const rect2 = { 50 | width2: 20, 51 | height2: 10, 52 | area2: 200 53 | } 54 | 55 | // Assigning it to a defaault value 56 | let { width2 = 1, height2, area2, perimeter2 = 60 } = rect2 57 | console.log(width2, height2, area2, perimeter2) // perimeter will be 60, width2 will not be updated 58 | 59 | // Getting object parameters without destructuring 60 | const calcPerimeter = rect => { 61 | return 2 * (rect.width + rect.height) 62 | } 63 | 64 | console.log(calcPerimeter(rect)) 65 | 66 | // Getting object parameters with destructuring 67 | const calculatePerimeter = ({ width, height }) => { 68 | return 2 * (width + height) 69 | } 70 | 71 | console.log(calculatePerimeter(rect)) 72 | 73 | // Destructuring object during iteration 74 | const todoList = [ 75 | { 76 | task: 'Prepare JS Test', 77 | time: '4/1/2020 8:30', 78 | completed: true 79 | }, 80 | { 81 | task: 'Give JS Test', 82 | time: '4/1/2020 10:00', 83 | completed: false 84 | }, 85 | { 86 | task: 'Assess Test Result', 87 | time: '4/1/2020 1:00', 88 | completed: false 89 | } 90 | ] 91 | 92 | for (const { task, time, completed } of todoList) { 93 | console.log(task, time, completed) 94 | } 95 | 96 | // The spread operator can be used to copy array 97 | const evens = [0, 2, 4, 6, 8, 10] 98 | const odds = [1, 3, 5, 7, 9] 99 | 100 | const evensCopy = [...evens] 101 | const oddsCopy = [...odds] 102 | const allCopy = [...evens, ...odds] 103 | 104 | console.log(evensCopy) 105 | console.log(oddsCopy) 106 | console.log(allCopy) 107 | 108 | // Spread can also be used to copy objects 109 | const rectCopy = { ...rect } 110 | console.log(rectCopy) 111 | 112 | // We can modify objects while copying 113 | const rectCopy2 = { ...rect, width: 15 } 114 | console.log(rectCopy2) 115 | 116 | // We can write arrow functions which take an unlimited amount of arguments using a spreaad operator 117 | const sumAllNums = (...args) => { 118 | console.log(args) 119 | let sum = 0 120 | for (const num of args) { 121 | sum += num 122 | } 123 | return sum 124 | } 125 | 126 | console.log(sumAllNums(1, 2, 3, 4, 5)) -------------------------------------------------------------------------------- /overview/main.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var __extends = (this && this.__extends) || (function () { 3 | var extendStatics = function (d, b) { 4 | extendStatics = Object.setPrototypeOf || 5 | ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || 6 | function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; 7 | return extendStatics(d, b); 8 | }; 9 | return function (d, b) { 10 | if (typeof b !== "function" && b !== null) 11 | throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); 12 | extendStatics(d, b); 13 | function __() { this.constructor = d; } 14 | d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); 15 | }; 16 | })(); 17 | Object.defineProperty(exports, "__esModule", { value: true }); 18 | var message = 'Welcome back!'; 19 | console.log(message); 20 | var x = 10; 21 | var y = 20; 22 | var sum; 23 | var title = 'Codevolution'; 24 | var isBeginner = true; 25 | var total = 0; 26 | var name = 'Eugene'; 27 | var sentence = "My name is ".concat(name, "\nI'm a beginner in Typescript"); 28 | console.log(sentence); 29 | var n = null; 30 | var u = undefined; 31 | var isNew = null; 32 | var myName = undefined; 33 | var list1 = [1, 2, 3]; 34 | var list2 = [1, 2, 3]; 35 | var person1 = ['Eugene', 34]; 36 | var Color; 37 | (function (Color) { 38 | Color[Color["Red"] = 5] = "Red"; 39 | Color[Color["Green"] = 6] = "Green"; 40 | Color[Color["Blue"] = 7] = "Blue"; 41 | })(Color || (Color = {})); 42 | ; 43 | var c = Color.Green; 44 | console.log(c); 45 | var randomValue = 10; 46 | randomValue = 'Eugene'; 47 | var myVariable = 10; 48 | // (myVariable as string).toUpperCase(); // This only casts the number as a string, but does not change the type of myVariable 49 | // Thus, it is still treated as a number and when we try to call toUpperCase() on it, we get an error. 50 | // Solve it by converting the number to a string first, then calling toUpperCase() on it. 51 | var aString = String(myVariable); 52 | console.log(aString.toUpperCase()); 53 | function hasName(obj) { 54 | return !!obj && 55 | typeof obj === 'object' && 56 | 'name' in obj; 57 | } 58 | if (hasName(myVariable)) { 59 | console.log(myVariable.name); 60 | } 61 | var a; 62 | a = 10; 63 | var b = 20; // Type inference 64 | // b = true; // Type error 65 | var multiType; 66 | multiType = 20; 67 | multiType = true; 68 | function add(num1, num2) { 69 | if (num2) 70 | return num1 + num2; 71 | else 72 | return num1; 73 | } 74 | var z = add(10, 20); 75 | console.log("z = ".concat(z)); 76 | var d = add(10); 77 | console.log("d = ".concat(d)); 78 | function fullName(person) { 79 | console.log("".concat(person.firstName, " ").concat(person.lastName)); 80 | } 81 | var p = { 82 | firstName: 'Bruce' 83 | }; 84 | fullName(p); 85 | var Employee = /** @class */ (function () { 86 | function Employee(name) { 87 | this.employeeName = name; 88 | } 89 | Employee.prototype.greet = function () { 90 | console.log("Good Morning ".concat(this.employeeName)); 91 | }; 92 | return Employee; 93 | }()); 94 | var e1 = new Employee('Eugene'); 95 | console.log(e1.employeeName); 96 | e1.greet(); 97 | var Manager = /** @class */ (function (_super) { 98 | __extends(Manager, _super); 99 | function Manager(managerName) { 100 | return _super.call(this, managerName) || this; 101 | } 102 | Manager.prototype.delegateWork = function () { 103 | console.log("Manager ".concat(this.employeeName, " delegating work")); 104 | }; 105 | return Manager; 106 | }(Employee)); 107 | var m1 = new Manager('Xinyi'); 108 | m1.delegateWork(); 109 | m1.greet(); 110 | console.log(m1.employeeName); 111 | -------------------------------------------------------------------------------- /basics-i/day16/main.js: -------------------------------------------------------------------------------- 1 | /* 2 | * JSON stands for JavaScript Object Notation. The format is text or string only. 3 | * It is a lightweight data format for storing and transporting, and is mostly used when 4 | * data is sent from a server to a client. It's easier than XML. 5 | * JavaScript Object and JSON are very similar and interchangable. 6 | * 7 | * - The key of a JSON object should be double quotes and it should be string. 8 | */ 9 | // JSON.parse() to change JSON into object; JSON.stringfy() to change object to JSON. 10 | var usersText = "{\n \"users\":[\n {\n \"firstName\":\"Asabeneh\",\n \"lastName\":\"Yetayeh\",\n \"age\":250,\n \"email\":\"asab@asb.com\"\n },\n {\n \"firstName\":\"Alex\",\n \"lastName\":\"James\",\n \"age\":25,\n \"email\":\"alex@alex.com\"\n },\n {\n \"firstName\":\"Lidiya\",\n \"lastName\":\"Tekle\",\n \"age\":28,\n \"email\":\"lidiya@lidiya.com\"\n }\n ]\n }"; 11 | var userObject = JSON.parse(usersText); 12 | console.log(userObject); 13 | // Using a reviver function as a formatter (e.g., formatting first name and last name) 14 | // ? is a ternary operator: condition ? execute if truthy : execute if falsy 15 | var userObject2 = JSON.parse(usersText, function (key, value) { 16 | var newValue = typeof value == 'string' && key != 'email' ? value.toUpperCase() : value; 17 | return newValue; 18 | }); 19 | console.log(userObject2); 20 | // Converting object to JSON 21 | var users = { 22 | Alex: { 23 | email: 'alex@alex.com', 24 | skills: ['HTML', 'CSS', 'JavaScript'], 25 | age: 20, 26 | isLoggedIn: false, 27 | points: 30 28 | }, 29 | Asab: { 30 | email: 'asab@asab.com', 31 | skills: [ 32 | 'HTML', 33 | 'CSS', 34 | 'JavaScript', 35 | 'Redux', 36 | 'MongoDB', 37 | 'Express', 38 | 'React', 39 | 'Node' 40 | ], 41 | age: 25, 42 | isLoggedIn: false, 43 | points: 50 44 | }, 45 | Brook: { 46 | email: 'daniel@daniel.com', 47 | skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux'], 48 | age: 30, 49 | isLoggedIn: true, 50 | points: 50 51 | }, 52 | Daniel: { 53 | email: 'daniel@alex.com', 54 | skills: ['HTML', 'CSS', 'JavaScript', 'Python'], 55 | age: 20, 56 | isLoggedIn: false, 57 | points: 40 58 | }, 59 | John: { 60 | email: 'john@john.com', 61 | skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux', 'Node.js'], 62 | age: 20, 63 | isLoggedIn: true, 64 | points: 50 65 | }, 66 | Thomas: { 67 | email: 'thomas@thomas.com', 68 | skills: ['HTML', 'CSS', 'JavaScript', 'React'], 69 | age: 20, 70 | isLoggedIn: false, 71 | points: 40 72 | }, 73 | Paul: { 74 | email: 'paul@paul.com', 75 | skills: [ 76 | 'HTML', 77 | 'CSS', 78 | 'JavaScript', 79 | 'MongoDB', 80 | 'Express', 81 | 'React', 82 | 'Node' 83 | ], 84 | age: 20, 85 | isLoggedIn: false, 86 | points: 40 87 | } 88 | }; 89 | var usersText2 = JSON.stringify(users); 90 | console.log(usersText2); 91 | // Using a filter array to filter the keys that we want to keep 92 | var user = { 93 | firstName: 'Asabeneh', 94 | lastName: 'Yetayeh', 95 | country: 'Finland', 96 | city: 'Helsinki', 97 | email: 'alex@alex.com', 98 | skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Pyhton'], 99 | age: 250, 100 | isLoggedIn: false, 101 | points: 30 102 | }; 103 | var userText = JSON.stringify(user, ['firstName', 'lastName']); 104 | console.log(userText); 105 | -------------------------------------------------------------------------------- /basics-i/day13/main.ts: -------------------------------------------------------------------------------- 1 | export { } 2 | /* 3 | * Console object methods 4 | * - console methods show output on the browser console 5 | * - document.write() show output on the browser document (view port) 6 | * - document.getElementById() to interact with the DOM using JavaScript 7 | */ 8 | 9 | 10 | // String interpolation using % 11 | console.log('%d %s of JavaScript', 30, 'Days') 12 | 13 | console.log('%c30 Days Of JavaScript', 'color:green') // log output is green 14 | 15 | // console.info() 16 | console.log('This in an info message') 17 | 18 | // console.warn() 19 | console.warn('This is a warning') 20 | 21 | // console.error() 22 | console.error('This is an error message') 23 | 24 | /* 25 | * console.table(): Displays tabular data as a table 26 | * - Takes one required argument, which must be an array or object 27 | * - And one additional argument of columns 28 | */ 29 | const names = ['Asabeneh', 'Brook', 'David', 'John'] 30 | console.table(names) 31 | 32 | const user = { 33 | name: 'Asabeneh', 34 | title: 'Programmer', 35 | country: 'Finland', 36 | city: 'Helsinki', 37 | age: 250 38 | } 39 | console.table(user) 40 | 41 | const countries = [ 42 | ['Finland', 'Helsinki'], 43 | ['Sweden', 'Stockholm'], 44 | ['Norway', 'Oslo'] 45 | ] 46 | console.table(countries) 47 | 48 | const users = [ 49 | { 50 | name: 'Asabeneh', 51 | title: 'Programmer', 52 | country: 'Finland', 53 | city: 'Helsinki', 54 | age: 250 55 | }, 56 | { 57 | name: 'Eyob', 58 | title: 'Teacher', 59 | country: 'Sweden', 60 | city: 'London', 61 | age: 25 62 | }, 63 | { 64 | name: 'Asab', 65 | title: 'Instructor', 66 | country: 'Norway', 67 | city: 'Oslo', 68 | age: 22 69 | }, 70 | { 71 | name: 'Matias', 72 | title: 'Developer', 73 | country: 'Denmark', 74 | city: 'Copenhagen', 75 | age: 28 76 | } 77 | ] 78 | console.table(users) 79 | 80 | // console.time(): starts a timer to track how long an operation takes 81 | console.time('Regular for loop') 82 | for (let i = 0; i < countries.length; i++) { 83 | console.log(countries[i][0], countries[i][1]) 84 | } 85 | console.timeEnd('Regular for loop') 86 | 87 | console.time('for of loop') 88 | for (const [name, city] of countries) { 89 | console.log(name, city) 90 | } 91 | console.timeEnd('for of loop') 92 | 93 | console.time('forEach loop') 94 | countries.forEach(([name, city]) => { 95 | console.log(name, city) 96 | }) 97 | console.timeEnd('forEach loop') 98 | 99 | // console.assert(): writes error message if the assert is false 100 | console.assert(4 > 3, '4 is greater than 3') 101 | console.assert(3 > 4, '3 is not greater than 4') 102 | 103 | for (let i = 0; i<= 10; i++) { 104 | let errorMessage = `${i} is not even` 105 | console.log(`The number is ${i}`) 106 | console.assert(i % 2 === 0, errorMessage) 107 | } 108 | 109 | // console.group(): group different log groups 110 | console.group('Names') 111 | console.log(names) 112 | console.groupEnd() 113 | 114 | console.group('Countries') 115 | console.log(countries) 116 | console.groupEnd() 117 | 118 | console.group('Users') 119 | console.log(user) 120 | console.log(users) 121 | console.groupEnd() 122 | 123 | // console.count(): prints the number of times console.count is called 124 | // Takes a string label parameter 125 | console.count('console.count() has been called') 126 | console.count('console.count() has been called') 127 | console.count('console.count() has been called') 128 | console.count('console.count() has been called') 129 | console.count('console.count() has been called') 130 | console.count('console.count() has been called') 131 | console.count('console.count() has been called') 132 | console.count('console.count() has been called') 133 | 134 | // console.clear(): clears the browser console 135 | // console.clear() 136 | -------------------------------------------------------------------------------- /basics-i/day16/main.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * JSON stands for JavaScript Object Notation. The format is text or string only. 3 | * It is a lightweight data format for storing and transporting, and is mostly used when 4 | * data is sent from a server to a client. It's easier than XML. 5 | * JavaScript Object and JSON are very similar and interchangable. 6 | * 7 | * - The key of a JSON object should be double quotes and it should be string. 8 | */ 9 | 10 | // JSON.parse() to change JSON into object; JSON.stringfy() to change object to JSON. 11 | const usersText = `{ 12 | "users":[ 13 | { 14 | "firstName":"Asabeneh", 15 | "lastName":"Yetayeh", 16 | "age":250, 17 | "email":"asab@asb.com" 18 | }, 19 | { 20 | "firstName":"Alex", 21 | "lastName":"James", 22 | "age":25, 23 | "email":"alex@alex.com" 24 | }, 25 | { 26 | "firstName":"Lidiya", 27 | "lastName":"Tekle", 28 | "age":28, 29 | "email":"lidiya@lidiya.com" 30 | } 31 | ] 32 | }` 33 | 34 | const userObject = JSON.parse(usersText) 35 | console.log(userObject) 36 | 37 | // Using a reviver function as a formatter (e.g., formatting first name and last name) 38 | // ? is a ternary operator: condition ? execute if truthy : execute if falsy 39 | const userObject2 = JSON.parse(usersText, (key, value) => { 40 | let newValue = typeof value == 'string' && key != 'email' ? value.toUpperCase() : value 41 | return newValue 42 | }) 43 | 44 | console.log(userObject2) 45 | 46 | // Converting object to JSON 47 | const users = { 48 | Alex: { 49 | email: 'alex@alex.com', 50 | skills: ['HTML', 'CSS', 'JavaScript'], 51 | age: 20, 52 | isLoggedIn: false, 53 | points: 30 54 | }, 55 | Asab: { 56 | email: 'asab@asab.com', 57 | skills: [ 58 | 'HTML', 59 | 'CSS', 60 | 'JavaScript', 61 | 'Redux', 62 | 'MongoDB', 63 | 'Express', 64 | 'React', 65 | 'Node' 66 | ], 67 | age: 25, 68 | isLoggedIn: false, 69 | points: 50 70 | }, 71 | Brook: { 72 | email: 'daniel@daniel.com', 73 | skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux'], 74 | age: 30, 75 | isLoggedIn: true, 76 | points: 50 77 | }, 78 | Daniel: { 79 | email: 'daniel@alex.com', 80 | skills: ['HTML', 'CSS', 'JavaScript', 'Python'], 81 | age: 20, 82 | isLoggedIn: false, 83 | points: 40 84 | }, 85 | John: { 86 | email: 'john@john.com', 87 | skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux', 'Node.js'], 88 | age: 20, 89 | isLoggedIn: true, 90 | points: 50 91 | }, 92 | Thomas: { 93 | email: 'thomas@thomas.com', 94 | skills: ['HTML', 'CSS', 'JavaScript', 'React'], 95 | age: 20, 96 | isLoggedIn: false, 97 | points: 40 98 | }, 99 | Paul: { 100 | email: 'paul@paul.com', 101 | skills: [ 102 | 'HTML', 103 | 'CSS', 104 | 'JavaScript', 105 | 'MongoDB', 106 | 'Express', 107 | 'React', 108 | 'Node' 109 | ], 110 | age: 20, 111 | isLoggedIn: false, 112 | points: 40 113 | } 114 | } 115 | 116 | const usersText2 = JSON.stringify(users) 117 | console.log(usersText2) 118 | 119 | // Using a filter array to filter the keys that we want to keep 120 | const user = { 121 | firstName: 'Asabeneh', 122 | lastName: 'Yetayeh', 123 | country: 'Finland', 124 | city: 'Helsinki', 125 | email: 'alex@alex.com', 126 | skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Pyhton'], 127 | age: 250, 128 | isLoggedIn: false, 129 | points: 30 130 | } 131 | 132 | const userText = JSON.stringify(user, ['firstName', 'lastName']) 133 | console.log(userText) -------------------------------------------------------------------------------- /basics-i/day12/main.js: -------------------------------------------------------------------------------- 1 | /* To use regexp, either use: 2 | * - A RegExp constructor, or 3 | * - Declare a RegExp pattern using two forward slashes followed by a flag. 4 | */ 5 | /* RegExp expressions take two parametrs: A required search pattern and an optional flag. 6 | * Flags are optional parameters in a regular expression which determine the type of searching: 7 | * - g: Global flag which means look for pattern in the whole text 8 | * - i: case insensitive flag 9 | * - m: multi-line flag 10 | */ 11 | // Declaring regexp without flags 12 | var pattern = 'love'; 13 | var regEx = new RegExp(pattern); 14 | // Declaring regexp with flags 15 | var regEx2 = new RegExp(pattern, 'gi'); 16 | // Creating pattern with RegExp Constructor 17 | var regEx3 = /love/gi; // regEx2 is equivalent to regEx3 18 | // test() checks for a match and returns true or false 19 | var str = 'I love TypeScript.'; 20 | var pattern2 = /love/; 21 | var result = pattern2.test(str); 22 | console.log(result); 23 | // match(): Returns an array containing all matches; null if no match found 24 | var result2 = str.match(pattern2); // Returns more information: [ 'love', index: 2, input: 'I love TypeScript.', groups: undefined ] 25 | console.log(result2); 26 | var pattern3 = /love/g; 27 | var result3 = str.match(pattern3); // Returns matches only: [ 'love' ] 28 | console.log(result3); 29 | // search(): Tests for a match and returns index; -1 if search fails 30 | var result4 = str.search(pattern3); 31 | console.log(result4); 32 | var str2 = 'I dont love Java'; 33 | var result5 = str2.search(pattern3); 34 | console.log(result5); 35 | // replace(): Replaces matched substring with a replacement substring 36 | var txt = 'Python is the most beautiful language that a human begin has ever created. \ 37 | I recommend python for a first programming language'; 38 | // Only the first instance in replaced 39 | var replacedTxt = txt.replace(/Python|python/, 'JavaScript'); 40 | console.log(replacedTxt); 41 | // Replaces pattern in the entire set 42 | var replacedTxt2 = txt.replace(/Python|python/g, 'JavaScript'); 43 | console.log(replacedTxt2); 44 | // Using the square bracket to include lower and upper case 45 | var applePattern = '[Aa]pple'; 46 | var appleTxt = 'Apple and banana are fruits. An old cliche says an apple a day a doctor way has been replaced by a banana a day keeps the doctor far far away. '; 47 | var appleMatches = appleTxt.match(applePattern); 48 | console.log(appleMatches); 49 | var applePattern2 = /[Aa]pple/g; 50 | var appleMatches2 = appleTxt.match(applePattern2); // Matches all instances and returns less info 51 | console.log(appleMatches2); 52 | // Using escape chars (\) 53 | var digitPattern = /\d/g; // Digits 54 | var txt2 = 'This regular expression example was made in January 12, 2020.'; 55 | var dMatches = txt2.match(digitPattern); 56 | console.log(dMatches); 57 | // Matching one or more times with plus (+) 58 | var digitPattern2 = /\d+/g; // Digits 59 | var dMatches2 = txt2.match(digitPattern2); 60 | console.log(dMatches2); 61 | // Matching any char with period (.) 62 | var aPattern = /[a]./g; 63 | var txt3 = 'Apple and banana are fruits'; 64 | var aMatches = txt3.match(aPattern); 65 | console.log(aMatches); 66 | // Matching zero or one times (?) 67 | var txt4 = 'I am not sure if there is a convention how to write the word e-mail.\ 68 | Some people write it email others may write it as Email or E-mail.'; 69 | var ePattern = /[Ee]-?mail/g; 70 | var eMatches = txt4.match(ePattern); 71 | console.log(eMatches); 72 | // Matching on substring length { } 73 | var txt5 = 'This regular expression example was made in December 6, 2019.'; 74 | var dPattern = /\d{4}/g; 75 | var dMatches3 = txt5.match(dPattern); 76 | console.log(dMatches3); 77 | var dPattern2 = /\d{1,4}/g; 78 | var dMatches4 = txt5.match(dPattern2); 79 | console.log(dMatches4); 80 | // Indicating start with (^) 81 | var startPattern = /^This/; 82 | var startMatches = txt5.match(startPattern); 83 | console.log(startMatches); 84 | // Negating with ^ within square brackets 85 | var negatePattern = /[^A-Za-z,. ]+/g; 86 | var negateMatches = txt5.match(negatePattern); 87 | console.log(negateMatches); 88 | // Exact matches (Still not sure how this works) 89 | var exactPattern = /^[A-Z][a-z]{3,12}$/; 90 | var exactMatches = exactPattern.test(txt5); 91 | console.log(exactMatches); 92 | -------------------------------------------------------------------------------- /basics-i/day18/main.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Callbacks take two parameters. The first is err and the second is result. If err is false, there 3 | * will not be an error; otherwise, error. 4 | * 5 | * Callbacks are functions passed as an argument to another function. They are executed after 6 | * another function has finished executing, thus the name "callback" 7 | * - https://www.w3schools.com/js/js_callback.asp 8 | * - https://codeburst.io/javascript-what-the-heck-is-a-callback-aba4da2deced 9 | */ 10 | const doSomething = callback => { 11 | setTimeout(() => { 12 | const skills = ['Python', 'Scala', 'TypeScript'] 13 | callback('It did not go well', skills) 14 | }, 0) 15 | } 16 | 17 | const callback = (err, result) => { 18 | if (err) { 19 | return console.log(err) 20 | } 21 | return console.log(result) 22 | } 23 | 24 | // Prints after 0.3 secs 25 | doSomething(callback) 26 | 27 | // Change callback err arg to false 28 | const doSomething2 = callback => { 29 | setTimeout(() => { 30 | const skills = ['Python', 'Scala', 'TypeScript'] 31 | callback(false, skills) 32 | }, 0) 33 | } 34 | 35 | // Prints after 0.2 secs, thus BEFORE the prior doSomething() is ran 36 | doSomething2(callback) 37 | 38 | /* 39 | * Promise: A way to handle async operations in JavaScript, allowing handlers with an async 40 | * action to have an eventual success value or failure reason. Instead of immediately returning 41 | * the final value, the async method returns a promise to supply the value sometime in the future. 42 | * 43 | * Promises have these states: 44 | * - pending: Initial state, neither fulfiled nor rejected 45 | * - fulfiled: Operation completed successfully 46 | * - rejected: Operation failed 47 | */ 48 | 49 | /* 50 | * Promises are created using the Promise constructor. Inside the constructor, it takes a 51 | * callback function, which has two parameters which are the resolve and reject functions. 52 | * - resolve: returns the result 53 | * - reject: returns as error in try catch 54 | */ 55 | 56 | const doPromise = new Promise((resolve, reject) => { 57 | setTimeout(() => { 58 | const skills = ['Python', 'Scala', 'TypeScript', 'SQL'] 59 | if (skills.length > 0) { 60 | resolve(skills) 61 | } else { 62 | reject('Something wrong has happened') 63 | } 64 | }, 0) 65 | }) 66 | 67 | // Settled with resolve 68 | doPromise 69 | .then(result => { 70 | console.log(result) 71 | }) 72 | .catch(error => console.log(error)) 73 | 74 | const doPromise2 = new Promise((resolve, reject) => { 75 | setTimeout(() => { 76 | const skills = ['Python', 'Scala', 'TypeScript', 'SQL'] 77 | if (skills.indexOf('Node') !== -1) { 78 | resolve('Fullstack dev') 79 | } else { 80 | reject('Something wrong has happened') 81 | } 82 | }, 0) 83 | }) 84 | 85 | // Settled with reject 86 | doPromise2 87 | .then(result => { 88 | console.log(result) 89 | }) 90 | .catch(error => console.log(error)) 91 | 92 | /* 93 | * Fetch API: To fetch resources across network, similar to XMLHttpRequest 94 | */ 95 | 96 | export { } 97 | 98 | const fetch = require('node-fetch'); 99 | 100 | const url = 'https://restcountries.eu/rest/v2/all' 101 | // fetch(url) // Where does response come from? 102 | // .then(response => response.json()) // Access API data as JSON 103 | // .then(data => { 104 | // console.log(data) 105 | // }) 106 | // .catch(error => console.log(error)) 107 | 108 | /* 109 | * Async and Await: An elegant way to handle promises. 110 | * - async: Having it infront of a function means the function will return a promise 111 | * - await: to access the value from the promise 112 | */ 113 | 114 | const square = async function (n) { 115 | return n * n 116 | } 117 | 118 | console.log(square(2)) 119 | 120 | const fetchData = async () => { 121 | try { 122 | const response = await fetch(url) 123 | const countries = await response.json() 124 | console.log(countries) 125 | } catch (err) { 126 | console.log(err) 127 | } 128 | } 129 | console.log('===== async and await') 130 | fetchData() -------------------------------------------------------------------------------- /basics-i/day12/main.ts: -------------------------------------------------------------------------------- 1 | /* To use regexp, either use: 2 | * - A RegExp constructor, or 3 | * - Declare a RegExp pattern using two forward slashes followed by a flag. 4 | */ 5 | 6 | /* RegExp expressions take two parametrs: A required search pattern and an optional flag. 7 | * Flags are optional parameters in a regular expression which determine the type of searching: 8 | * - g: Global flag which means look for pattern in the whole text 9 | * - i: case insensitive flag 10 | * - m: multi-line flag 11 | */ 12 | 13 | // Declaring regexp without flags 14 | let pattern = 'love' 15 | let regEx = new RegExp(pattern) 16 | 17 | // Declaring regexp with flags 18 | let regEx2 = new RegExp(pattern, 'gi') 19 | 20 | // Creating pattern with RegExp Constructor 21 | let regEx3 = /love/gi // regEx2 is equivalent to regEx3 22 | 23 | // test() checks for a match and returns true or false 24 | const str = 'I love TypeScript.' 25 | const pattern2 = /love/ 26 | const result = pattern2.test(str) 27 | console.log(result) 28 | 29 | // match(): Returns an array containing all matches; null if no match found 30 | const result2 = str.match(pattern2) // Returns more information: [ 'love', index: 2, input: 'I love TypeScript.', groups: undefined ] 31 | console.log(result2) 32 | 33 | const pattern3 = /love/g 34 | const result3 = str.match(pattern3) // Returns matches only: [ 'love' ] 35 | console.log(result3) 36 | 37 | // search(): Tests for a match and returns index; -1 if search fails 38 | const result4 = str.search(pattern3) 39 | console.log(result4) 40 | 41 | const str2 = 'I dont love Java' 42 | const result5 = str2.search(pattern3) 43 | console.log(result5) 44 | 45 | // replace(): Replaces matched substring with a replacement substring 46 | const txt = 'Python is the most beautiful language that a human begin has ever created. \ 47 | I recommend python for a first programming language' 48 | 49 | // Only the first instance in replaced 50 | let replacedTxt = txt.replace(/Python|python/, 'JavaScript') 51 | console.log(replacedTxt) 52 | 53 | // Replaces pattern in the entire set 54 | let replacedTxt2 = txt.replace(/Python|python/g, 'JavaScript') 55 | console.log(replacedTxt2) 56 | 57 | // Using the square bracket to include lower and upper case 58 | const applePattern = '[Aa]pple' 59 | const appleTxt = 'Apple and banana are fruits. An old cliche says an apple a day a doctor way has been replaced by a banana a day keeps the doctor far far away. ' 60 | const appleMatches = appleTxt.match(applePattern) 61 | console.log(appleMatches) 62 | 63 | const applePattern2 = /[Aa]pple/g 64 | const appleMatches2 = appleTxt.match(applePattern2) // Matches all instances and returns less info 65 | console.log(appleMatches2) 66 | 67 | // Using escape chars (\) 68 | const digitPattern = /\d/g // Digits 69 | const txt2 = 'This regular expression example was made in January 12, 2020.' 70 | const dMatches = txt2.match(digitPattern) 71 | console.log(dMatches) 72 | 73 | // Matching one or more times with plus (+) 74 | const digitPattern2 = /\d+/g // Digits 75 | const dMatches2 = txt2.match(digitPattern2) 76 | console.log(dMatches2) 77 | 78 | // Matching any char with period (.) 79 | const aPattern = /[a]./g 80 | const txt3 = 'Apple and banana are fruits' 81 | const aMatches = txt3.match(aPattern) 82 | console.log(aMatches) 83 | 84 | // Matching zero or one times (?) 85 | const txt4 = 'I am not sure if there is a convention how to write the word e-mail.\ 86 | Some people write it email others may write it as Email or E-mail.' 87 | const ePattern = /[Ee]-?mail/g 88 | const eMatches = txt4.match(ePattern) 89 | console.log(eMatches) 90 | 91 | // Matching on substring length { } 92 | const txt5 = 'This regular expression example was made in December 6, 2019.' 93 | const dPattern = /\d{4}/g 94 | const dMatches3 = txt5.match(dPattern) 95 | console.log(dMatches3) 96 | 97 | const dPattern2 = /\d{1,4}/g 98 | const dMatches4 = txt5.match(dPattern2) 99 | console.log(dMatches4) 100 | 101 | // Indicating start with (^) 102 | const startPattern = /^This/ 103 | const startMatches = txt5.match(startPattern) 104 | console.log(startMatches) 105 | 106 | // Negating with ^ within square brackets 107 | const negatePattern = /[^A-Za-z,. ]+/g 108 | const negateMatches = txt5.match(negatePattern) 109 | console.log(negateMatches) 110 | 111 | // Exact matches (Still not sure how this works) 112 | let exactPattern = /^[A-Z][a-z]{3,12}$/ 113 | const exactMatches = exactPattern.test(txt5) 114 | console.log(exactMatches) -------------------------------------------------------------------------------- /basics-i/day15/main.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Classes are object constructors that we can instantiate to create an object (from week 8). 3 | */ 4 | 5 | // Instatiating a class: To create an object from a class 6 | class Person { 7 | 8 | } 9 | 10 | const person = new Person() 11 | console.log(person) 12 | 13 | /* 14 | * Constructor is a builtin function to create a blueprint for objects 15 | * use this keyword to attach constructor parameters into the class 16 | */ 17 | 18 | class Person2 { 19 | constructor(firstName, lastName) { 20 | console.log(this) 21 | 22 | this.firstName = firstName 23 | this.lastName = lastName 24 | } 25 | } 26 | 27 | const person2 = new Person2('Eugene', 'Yan') 28 | console.log(person2) 29 | 30 | // Add default values 31 | class Person3 { 32 | constructor(firstName = 'John', lastName = 'Doe') { 33 | this.firstName = firstName 34 | this.lastName = lastName 35 | } 36 | } 37 | 38 | const person3 = new Person3() 39 | console.log(person3) 40 | 41 | // Adding class methods 42 | class Person4 { 43 | constructor(firstName = 'John', lastName = 'Doe') { 44 | this.firstName = firstName 45 | this.lastName = lastName 46 | } 47 | 48 | getFullName() { 49 | const fullName = `${this.firstName} ${this.lastName}` 50 | return fullName 51 | } 52 | } 53 | 54 | const person4 = new Person4() 55 | console.log(person4.getFullName()) 56 | 57 | // Getters and setters 58 | class Person5 { 59 | constructor(firstName = 'John', lastName = 'Doe') { 60 | this.firstName = firstName 61 | this.lastName = lastName 62 | this.score = 0 63 | this.skills = [] 64 | } 65 | 66 | get getFullName() { 67 | const fullName = `${this.firstName} ${this.lastName}` 68 | return fullName 69 | } 70 | 71 | get getScore() { 72 | return this.score 73 | } 74 | 75 | get getSkills() { 76 | return this.skills 77 | } 78 | 79 | set setScore(score) { 80 | this.score += score 81 | } 82 | 83 | set setSkill(skill) { 84 | this.skills.push(skill) 85 | } 86 | } 87 | 88 | const person5 = new Person5() 89 | console.log(person5.getFullName) // No () when calling getter 90 | console.log(person5.getScore) 91 | console.log(person5.getSkills) 92 | 93 | person5.setScore = 1 94 | person5.setSkill = 'Python' 95 | person5.setSkill = 'Scala' 96 | person5.setSkill = 'TypeScript' 97 | console.log(person5.getScore) 98 | console.log(person5.getSkills) 99 | 100 | // Static methods: Not called on instances of the class, but the class itself. 101 | // They're often utility functions, and are called directly from the class 102 | class Person6 { 103 | constructor(firstName = 'John', lastName = 'Doe') { 104 | this.firstName = firstName 105 | this.lastName = lastName 106 | this.score = 0 107 | this.skills = [] 108 | } 109 | 110 | static showDateTime() { 111 | let now = new Date() 112 | let year = now.getFullYear() 113 | let month = now.getMonth() + 1 114 | let date = now.getDate() 115 | 116 | let fullDate = `${year}-${month}-${date}` 117 | return fullDate 118 | } 119 | } 120 | 121 | console.log(Person6.showDateTime()) 122 | 123 | // Inheritance: Child class can access all properties of parent class, reducing code repetition 124 | class Student extends Person5 { 125 | saySomething() { 126 | console.log('I am a child of Person5') // Not sure why this causes undefined in log 127 | } 128 | } 129 | 130 | const student = new Student() 131 | console.log(student) 132 | console.log(student.saySomething()) 133 | console.log(student.getFullName) 134 | 135 | // Overriding methods: If we want to add properties, we'll need to use the constructor function 136 | // in the child class too. We can thes call super() to access all properties from the parent class. 137 | class Student2 extends Person5 { 138 | constructor(firstName, lastName, gender) { 139 | super(firstName, lastName) 140 | this.gender = gender 141 | } 142 | 143 | saySomething() { 144 | console.log('I am a child of Person5') // Not sure why this causes undefined in log 145 | } 146 | 147 | get getFullNameWithGender() { 148 | let fullName = this.getFullName 149 | let fullNameWithGender = `${fullName} (gender: ${this.gender})` 150 | return fullNameWithGender 151 | } 152 | } 153 | 154 | const student2 = new Student2('Eugene', 'Yan', 'M') 155 | console.log(student2.getFullNameWithGender) -------------------------------------------------------------------------------- /basics-i/day9/main.ts: -------------------------------------------------------------------------------- 1 | export { } 2 | 3 | /* Higher order functions 4 | * Take another functino as a parameter or return a function as a value 5 | */ 6 | 7 | // Callback: Function that can be passed as parameter to another function 8 | const callback = (n) => { 9 | return n ** 2 10 | } 11 | 12 | function cube(callback, n) { 13 | return callback(n) * n 14 | } 15 | 16 | console.log(callback(3)) 17 | console.log(cube(callback, 3)) 18 | 19 | // Returning a function 20 | const higherOrder = n => { 21 | const doSomething = m => { 22 | const doWhatever = t => { 23 | return 2 * n + 3 * m + t 24 | } 25 | return doWhatever 26 | } 27 | return doSomething 28 | } 29 | 30 | console.log(higherOrder(2)(3)(4)) 31 | 32 | // When to use callback 33 | const numbers = [1, 2, 3, 4] 34 | 35 | const sumArray = arr => { 36 | let sum = 0 37 | const callback = function (element) { 38 | sum += element 39 | } 40 | numbers.forEach(callback) 41 | return sum 42 | } 43 | 44 | console.log(sumArray(numbers)) 45 | 46 | // setInterval: To do some activity continously within some interval of time 47 | function sayHello() { 48 | console.log('Hello!') 49 | } 50 | 51 | // setInterval(sayHello, 2000) // Prints hello every 2 seconds 52 | 53 | // setTimeout: To execute some action some time in the future 54 | function sayGoodbye() { 55 | console.log('Goodbye!') 56 | } 57 | 58 | // setTimeout(sayGoodbye, 2000) 59 | 60 | /* Functional Programming 61 | * These built-in methods take a callback function 62 | */ 63 | 64 | 65 | // forEach: Iterate an array of elements, used only with arrays 66 | // Takes callback function with elements, with optional index and array 67 | numbers.forEach(function (element, index, arr) { 68 | console.log(index, element, numbers) 69 | }) 70 | 71 | let sum = 0 72 | numbers.forEach(num => sum += num) 73 | 74 | console.log(sum) 75 | 76 | const countries = ['Finland', 'Denmark', 'Sweden', 'Norway', 'Iceland'] 77 | countries.forEach((element) => console.log(element.toUpperCase())) 78 | 79 | // map: Iterate an array of elements and modify the array elements 80 | const numbersSquare = numbers.map((num) => num * num) 81 | console.log(numbersSquare) 82 | 83 | const countriesUpper = countries.map((country) => country.toUpperCase()) 84 | console.log(countriesUpper) 85 | 86 | const countriesThreeChar = countries.map((country) => country.slice(0, 3).toUpperCase()) 87 | console.log(countriesThreeChar) 88 | 89 | // filter: Filter out items which meet filtering conditions 90 | const countriesWithLand = countries.filter((country) => country.includes('land')) 91 | console.log(countriesWithLand) 92 | 93 | const countriesSixChar = countries.filter((country) => country.length === 6) 94 | console.log(countriesSixChar) 95 | 96 | // reduce: Takes accumulator, current, and optional initial value and returns a single value 97 | // It's good practice to define the initial value. If no initial value is specified, 98 | // it will use the array's first value 99 | // 100 | // arr.reduce((acc, cur) => { 101 | // // some operations goes here before returning a value 102 | // return 103 | // }, initialValue) 104 | 105 | const numbersSum = numbers.reduce((acc, cur) => acc + cur, 0) 106 | console.log(numbersSum) 107 | 108 | // every: Check if all elements meet a condition and returns a boolean 109 | const allStr = countries.every((country) => typeof country === 'string') 110 | 111 | console.log(allStr) 112 | 113 | // find: Return the first element that satisfies condition 114 | const hasWay = countries.find((country) => country.includes('way')) 115 | console.log(hasWay) 116 | 117 | // findIndex: Returns position of first element that satisfies condition 118 | const hasWayIndex = countries.findIndex((country) => country.includes('way')) 119 | console.log(hasWayIndex) 120 | 121 | // some: Check if some elements meet the condition (NOTE: THIS IS ANY) 122 | console.log(countries.some((country) => country.includes('e'))) 123 | console.log(countries.some((country) => country.includes('o'))) 124 | console.log(countries.some((country) => country.includes('x'))) 125 | 126 | // sort: Arranges arrays in ascending or descentding order 127 | // By default, sorts values as strings. Works well for string array but not numbers 128 | console.log(countries.sort()) 129 | 130 | // To sort numbers correct, we need to use a callback function 131 | const nums = [9.81, 3.14, 100, 37] 132 | console.log(nums.sort()) 133 | 134 | nums.sort(function (a, b) { 135 | return a - b 136 | }) 137 | console.log(nums) 138 | 139 | nums.sort(function (a, b) { 140 | return b - a 141 | }) 142 | console.log(nums) -------------------------------------------------------------------------------- /basics-i/day10/main.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var __values = (this && this.__values) || function(o) { 3 | var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; 4 | if (m) return m.call(o); 5 | if (o && typeof o.length === "number") return { 6 | next: function () { 7 | if (o && i >= o.length) o = void 0; 8 | return { value: o && o[i++], done: !o }; 9 | } 10 | }; 11 | throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); 12 | }; 13 | var __read = (this && this.__read) || function (o, n) { 14 | var m = typeof Symbol === "function" && o[Symbol.iterator]; 15 | if (!m) return o; 16 | var i = m.call(o), r, ar = [], e; 17 | try { 18 | while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); 19 | } 20 | catch (error) { e = { error: error }; } 21 | finally { 22 | try { 23 | if (r && !r.done && (m = i["return"])) m.call(i); 24 | } 25 | finally { if (e) throw e.error; } 26 | } 27 | return ar; 28 | }; 29 | var __spread = (this && this.__spread) || function () { 30 | for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); 31 | return ar; 32 | }; 33 | var e_1, _a, e_2, _b; 34 | exports.__esModule = true; 35 | // Create empty set 36 | var companies = new Set(); 37 | console.log(companies); 38 | // Create set from array 39 | var languages = [ 40 | 'English', 41 | 'Finnish', 42 | 'English', 43 | 'French', 44 | 'Spanish', 45 | 'English', 46 | 'French', 47 | ]; 48 | var setOfLanguages = new Set(languages); 49 | console.log(setOfLanguages); 50 | try { 51 | // We can iterate through sets 52 | for (var setOfLanguages_1 = __values(setOfLanguages), setOfLanguages_1_1 = setOfLanguages_1.next(); !setOfLanguages_1_1.done; setOfLanguages_1_1 = setOfLanguages_1.next()) { 53 | var language = setOfLanguages_1_1.value; 54 | console.log(language); 55 | } 56 | } 57 | catch (e_1_1) { e_1 = { error: e_1_1 }; } 58 | finally { 59 | try { 60 | if (setOfLanguages_1_1 && !setOfLanguages_1_1.done && (_a = setOfLanguages_1["return"])) _a.call(setOfLanguages_1); 61 | } 62 | finally { if (e_1) throw e_1.error; } 63 | } 64 | // Adding elements to set 65 | console.log(companies.size); 66 | companies.add('Facebook'); 67 | companies.add('Amazon'); 68 | companies.add('Apple'); 69 | companies.add('Netflix'); 70 | companies.add('Google'); 71 | console.log(companies.size); 72 | console.log(companies); 73 | // Deleting an element from a set 74 | companies["delete"]('Google'); 75 | console.log(companies.size); 76 | console.log(companies); 77 | // Checking if in element 78 | console.log(companies.has('Apple')); 79 | console.log(companies.has('Snapchat')); 80 | // Clearing the set 81 | companies.clear(); 82 | console.log(companies); 83 | // Union of sets 84 | var a = [1, 2, 3, 4, 5]; 85 | var b = [3, 4, 5, 6]; 86 | var c = __spread(a, b); 87 | var A = new Set(a); 88 | var B = new Set(b); 89 | var C = new Set(c); 90 | console.log(C); 91 | // Intersection of sets 92 | var cIntersect = a.filter(function (num) { return B.has(num); }); 93 | console.log(cIntersect); 94 | // Difference of sets 95 | var cDiff = a.filter(function (num) { return !B.has(num); }); 96 | console.log(cDiff); 97 | // Creating an empty Map 98 | var map = new Map(); 99 | console.log(map); 100 | // Creating a Map from array 101 | var countries = [ 102 | ['Finland', 'Helsinki'], 103 | ['Sweden', 'Stockholm'], 104 | ['Norway', 'Oslo'], 105 | ]; 106 | var mapCountries = new Map(countries); 107 | console.log(mapCountries.size); 108 | console.log(mapCountries); 109 | // Adding values to map 110 | var countriesMap = new Map(); 111 | console.log(countriesMap.size); 112 | countriesMap.set('Finland', 'Helsinki'); 113 | countriesMap.set('Sweden', 'Stockholm'); 114 | countriesMap.set('Norway', 'Oslo'); 115 | console.log(countriesMap.size); 116 | console.log(countriesMap); 117 | // Getting value from Map 118 | console.log(countriesMap.get('Finland')); 119 | // Checking key in Map 120 | console.log(countriesMap.has('Finland')); 121 | try { 122 | // Get all values from Map via loop 123 | for (var countriesMap_1 = __values(countriesMap), countriesMap_1_1 = countriesMap_1.next(); !countriesMap_1_1.done; countriesMap_1_1 = countriesMap_1.next()) { 124 | var country = countriesMap_1_1.value; 125 | console.log(country); 126 | } 127 | } 128 | catch (e_2_1) { e_2 = { error: e_2_1 }; } 129 | finally { 130 | try { 131 | if (countriesMap_1_1 && !countriesMap_1_1.done && (_b = countriesMap_1["return"])) _b.call(countriesMap_1); 132 | } 133 | finally { if (e_2) throw e_2.error; } 134 | } 135 | -------------------------------------------------------------------------------- /basics-i/day9/main.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | exports.__esModule = true; 3 | /* Higher order functions 4 | * Take another functino as a parameter or return a function as a value 5 | */ 6 | // Callback: Function that can be passed as parameter to another function 7 | var callback = function (n) { 8 | return Math.pow(n, 2); 9 | }; 10 | function cube(callback, n) { 11 | return callback(n) * n; 12 | } 13 | console.log(callback(3)); 14 | console.log(cube(callback, 3)); 15 | // Returning a function 16 | var higherOrder = function (n) { 17 | var doSomething = function (m) { 18 | var doWhatever = function (t) { 19 | return 2 * n + 3 * m + t; 20 | }; 21 | return doWhatever; 22 | }; 23 | return doSomething; 24 | }; 25 | console.log(higherOrder(2)(3)(4)); 26 | // When to use callback 27 | var numbers = [1, 2, 3, 4]; 28 | var sumArray = function (arr) { 29 | var sum = 0; 30 | var callback = function (element) { 31 | sum += element; 32 | }; 33 | numbers.forEach(callback); 34 | return sum; 35 | }; 36 | console.log(sumArray(numbers)); 37 | // setInterval: To do some activity continously within some interval of time 38 | function sayHello() { 39 | console.log('Hello!'); 40 | } 41 | // setInterval(sayHello, 2000) // Prints hello every 2 seconds 42 | // setTimeout: To execute some action some time in the future 43 | function sayGoodbye() { 44 | console.log('Goodbye!'); 45 | } 46 | // setTimeout(sayGoodbye, 2000) 47 | /* Functional Programming 48 | * These built-in methods take a callback function 49 | */ 50 | // forEach: Iterate an array of elements, used only with arrays 51 | // Takes callback function with elements, with optional index and array 52 | numbers.forEach(function (element, index, arr) { 53 | console.log(index, element, numbers); 54 | }); 55 | var sum = 0; 56 | numbers.forEach(function (num) { return sum += num; }); 57 | console.log(sum); 58 | var countries = ['Finland', 'Denmark', 'Sweden', 'Norway', 'Iceland']; 59 | countries.forEach(function (element) { return console.log(element.toUpperCase()); }); 60 | // map: Iterate an array of elements and modify the array elements 61 | var numbersSquare = numbers.map(function (num) { return num * num; }); 62 | console.log(numbersSquare); 63 | var countriesUpper = countries.map(function (country) { return country.toUpperCase(); }); 64 | console.log(countriesUpper); 65 | var countriesThreeChar = countries.map(function (country) { return country.slice(0, 3).toUpperCase(); }); 66 | console.log(countriesThreeChar); 67 | // filter: Filter out items which meet filtering conditions 68 | var countriesWithLand = countries.filter(function (country) { return country.includes('land'); }); 69 | console.log(countriesWithLand); 70 | var countriesSixChar = countries.filter(function (country) { return country.length === 6; }); 71 | console.log(countriesSixChar); 72 | // reduce: Takes accumulator, current, and optional initial value and returns a single value 73 | // It's good practice to define the initial value. If no initial value is specified, 74 | // it will use the array's first value 75 | // 76 | // arr.reduce((acc, cur) => { 77 | // // some operations goes here before returning a value 78 | // return 79 | // }, initialValue) 80 | var numbersSum = numbers.reduce(function (acc, cur) { return acc + cur; }, 0); 81 | console.log(numbersSum); 82 | // every: Check if all elements meet a condition and returns a boolean 83 | var allStr = countries.every(function (country) { return typeof country === 'string'; }); 84 | console.log(allStr); 85 | // find: Return the first element that satisfies condition 86 | var hasWay = countries.find(function (country) { return country.includes('way'); }); 87 | console.log(hasWay); 88 | // findIndex: Returns position of first element that satisfies condition 89 | var hasWayIndex = countries.findIndex(function (country) { return country.includes('way'); }); 90 | console.log(hasWayIndex); 91 | // some: Check if some elements meet the condition (NOTE: THIS IS ANY) 92 | console.log(countries.some(function (country) { return country.includes('e'); })); 93 | console.log(countries.some(function (country) { return country.includes('o'); })); 94 | console.log(countries.some(function (country) { return country.includes('x'); })); 95 | // sort: Arranges arrays in ascending or descentding order 96 | // By default, sorts values as strings. Works well for string array but not numbers 97 | console.log(countries.sort()); 98 | // To sort numbers correct, we need to use a callback function 99 | var nums = [9.81, 3.14, 100, 37]; 100 | console.log(nums.sort()); 101 | nums.sort(function (a, b) { 102 | return a - b; 103 | }); 104 | console.log(nums); 105 | nums.sort(function (a, b) { 106 | return b - a; 107 | }); 108 | console.log(nums); 109 | -------------------------------------------------------------------------------- /basics-i/day13/main.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var __values = (this && this.__values) || function(o) { 3 | var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; 4 | if (m) return m.call(o); 5 | if (o && typeof o.length === "number") return { 6 | next: function () { 7 | if (o && i >= o.length) o = void 0; 8 | return { value: o && o[i++], done: !o }; 9 | } 10 | }; 11 | throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); 12 | }; 13 | var __read = (this && this.__read) || function (o, n) { 14 | var m = typeof Symbol === "function" && o[Symbol.iterator]; 15 | if (!m) return o; 16 | var i = m.call(o), r, ar = [], e; 17 | try { 18 | while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); 19 | } 20 | catch (error) { e = { error: error }; } 21 | finally { 22 | try { 23 | if (r && !r.done && (m = i["return"])) m.call(i); 24 | } 25 | finally { if (e) throw e.error; } 26 | } 27 | return ar; 28 | }; 29 | var e_1, _a; 30 | exports.__esModule = true; 31 | /* 32 | * Console object methods 33 | * - console methods show output on the browser console 34 | * - document.write() show output on the browser document (view port) 35 | * - document.getElementById() to interact with the DOM using JavaScript 36 | */ 37 | // String interpolation using % 38 | console.log('%d %s of JavaScript', 30, 'Days'); 39 | console.log('%c30 Days Of JavaScript', 'color:green'); // log output is green 40 | // console.info() 41 | console.log('This in an info message'); 42 | // console.warn() 43 | console.warn('This is a warning'); 44 | // console.error() 45 | console.error('This is an error message'); 46 | /* 47 | * console.table(): Displays tabular data as a table 48 | * - Takes one required argument, which must be an array or object 49 | * - And one additional argument of columns 50 | */ 51 | var names = ['Asabeneh', 'Brook', 'David', 'John']; 52 | console.table(names); 53 | var user = { 54 | name: 'Asabeneh', 55 | title: 'Programmer', 56 | country: 'Finland', 57 | city: 'Helsinki', 58 | age: 250 59 | }; 60 | console.table(user); 61 | var countries = [ 62 | ['Finland', 'Helsinki'], 63 | ['Sweden', 'Stockholm'], 64 | ['Norway', 'Oslo'] 65 | ]; 66 | console.table(countries); 67 | var users = [ 68 | { 69 | name: 'Asabeneh', 70 | title: 'Programmer', 71 | country: 'Finland', 72 | city: 'Helsinki', 73 | age: 250 74 | }, 75 | { 76 | name: 'Eyob', 77 | title: 'Teacher', 78 | country: 'Sweden', 79 | city: 'London', 80 | age: 25 81 | }, 82 | { 83 | name: 'Asab', 84 | title: 'Instructor', 85 | country: 'Norway', 86 | city: 'Oslo', 87 | age: 22 88 | }, 89 | { 90 | name: 'Matias', 91 | title: 'Developer', 92 | country: 'Denmark', 93 | city: 'Copenhagen', 94 | age: 28 95 | } 96 | ]; 97 | console.table(users); 98 | // console.time(): starts a timer to track how long an operation takes 99 | console.time('Regular for loop'); 100 | for (var i = 0; i < countries.length; i++) { 101 | console.log(countries[i][0], countries[i][1]); 102 | } 103 | console.timeEnd('Regular for loop'); 104 | console.time('for of loop'); 105 | try { 106 | for (var countries_1 = __values(countries), countries_1_1 = countries_1.next(); !countries_1_1.done; countries_1_1 = countries_1.next()) { 107 | var _b = __read(countries_1_1.value, 2), name_1 = _b[0], city = _b[1]; 108 | console.log(name_1, city); 109 | } 110 | } 111 | catch (e_1_1) { e_1 = { error: e_1_1 }; } 112 | finally { 113 | try { 114 | if (countries_1_1 && !countries_1_1.done && (_a = countries_1["return"])) _a.call(countries_1); 115 | } 116 | finally { if (e_1) throw e_1.error; } 117 | } 118 | console.timeEnd('for of loop'); 119 | console.time('forEach loop'); 120 | countries.forEach(function (_a) { 121 | var _b = __read(_a, 2), name = _b[0], city = _b[1]; 122 | console.log(name, city); 123 | }); 124 | console.timeEnd('forEach loop'); 125 | // console.assert(): writes error message if the assert is false 126 | console.assert(4 > 3, '4 is greater than 3'); 127 | console.assert(3 > 4, '3 is not greater than 4'); 128 | for (var i = 0; i <= 10; i++) { 129 | var errorMessage = i + " is not even"; 130 | console.log("The number is " + i); 131 | console.assert(i % 2 === 0, errorMessage); 132 | } 133 | // console.group(): group different log groups 134 | console.group('Names'); 135 | console.log(names); 136 | console.groupEnd(); 137 | console.group('Countries'); 138 | console.log(countries); 139 | console.groupEnd(); 140 | console.group('Users'); 141 | console.log(user); 142 | console.log(users); 143 | console.groupEnd(); 144 | // console.count(): prints the number of times console.count is called 145 | // Takes a string label parameter 146 | console.count('console.count() has been called'); 147 | console.count('console.count() has been called'); 148 | console.count('console.count() has been called'); 149 | console.count('console.count() has been called'); 150 | console.count('console.count() has been called'); 151 | console.count('console.count() has been called'); 152 | console.count('console.count() has been called'); 153 | console.count('console.count() has been called'); 154 | // console.clear(): clears the browser console 155 | // console.clear() 156 | -------------------------------------------------------------------------------- /basics-i/day8/main.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | exports.__esModule = true; 3 | var a = 'JavaScript'; // Global scope 4 | var b = 10; // Global scope 5 | function letsLearnScope() { 6 | console.log("The awesome of " + a + " is " + b); 7 | var c = 30; 8 | if (true) { 9 | var a_1 = 'Python'; // Local scope 10 | var b_1 = 100; // Local scope 11 | console.log("The awesome of " + a_1 + " is " + b_1); 12 | } 13 | console.log("The awesome of " + a + " is " + b); 14 | } 15 | letsLearnScope(); 16 | console.log("The awesome of " + a + " is " + b); 17 | // var vs. let 18 | function letsLearnScope2() { 19 | var gravity = 9.81; 20 | console.log(gravity); 21 | } 22 | // console.log(gravity) // This will fail with var or let 23 | if (true) { 24 | var gravity = 9.81; 25 | console.log(gravity); 26 | } 27 | console.log(gravity); // This works with var and let, but VS code complains about let 28 | for (var i = 0; i < 3; i++) { 29 | console.log("Loop: " + i); 30 | } 31 | console.log(i); 32 | // From ES6 and above, there's let and const. Suggest to only use let and const, and use const for 33 | // values which will will not change (like val for scala.) 34 | /* 35 | * Objects: Everything can be an object. Objects have properties and properties have values. 36 | * Thus, objects are key value pairs. The order of the key is not reserved. 37 | * To create objects, we use two curly brackets. 38 | */ 39 | var rectangle = { 40 | length: 20, 41 | width: 20 42 | }; 43 | console.log(rectangle); 44 | var person = { 45 | firstName: 'Eugene', 46 | lastName: 'Yan', 47 | age: 34, 48 | country: 'United States', 49 | city: 'Seattle', 50 | skills: [ 51 | 'SQL', 52 | 'Python', 53 | 'Scala', 54 | 'TypeScript', 55 | 'Docker' 56 | ], 57 | isMarried: true, 58 | 'two word key': true, 59 | getFullName: function () { 60 | return "Full name is " + this.firstName + " " + this.lastName; // this is like python's self 61 | } 62 | }; 63 | console.log(person); 64 | // Accessing values from objects 65 | console.log(person.firstName); 66 | console.log(person['firstName']); 67 | console.log(person['two word key']); // If the key is two words 68 | console.log(person.getFullName()); 69 | // Adding new keys 70 | person['nationality'] = 'Singaporean'; // Though VS Code complains about this, it works 71 | person.skills.push('Spark'); 72 | console.log(person['nationality']); 73 | // Object.assign: To copy object without modifying the original object 74 | var copyperson = Object.assign({}, person); 75 | console.log(copyperson); 76 | var personKeys = Object.keys(person); 77 | console.log(personKeys); 78 | var personValues = Object.values(person); 79 | console.log(personValues); 80 | var personEntries = Object.entries(person); 81 | console.log(personEntries); 82 | console.log(person.hasOwnProperty('firstName')); 83 | console.log(person.hasOwnProperty('middleName')); 84 | // Exercises Level 2 85 | var users = { 86 | Alex: { 87 | email: 'alex@alex.com', 88 | skills: ['HTML', 'CSS', 'JavaScript'], 89 | age: 20, 90 | isLoggedIn: false, 91 | points: 30 92 | }, 93 | Asab: { 94 | email: 'asab@asab.com', 95 | skills: ['HTML', 'CSS', 'JavaScript', 'Redux', 'MongoDB', 'Express', 'React', 'Node'], 96 | age: 25, 97 | isLoggedIn: false, 98 | points: 50 99 | }, 100 | Brook: { 101 | email: 'daniel@daniel.com', 102 | skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux'], 103 | age: 30, 104 | isLoggedIn: true, 105 | points: 50 106 | }, 107 | Daniel: { 108 | email: 'daniel@alex.com', 109 | skills: ['HTML', 'CSS', 'JavaScript', 'Python'], 110 | age: 20, 111 | isLoggedIn: false, 112 | points: 40 113 | }, 114 | John: { 115 | email: 'john@john.com', 116 | skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux', 'Node.js'], 117 | age: 20, 118 | isLoggedIn: true, 119 | points: 50 120 | }, 121 | Thomas: { 122 | email: 'thomas@thomas.com', 123 | skills: ['HTML', 'CSS', 'JavaScript', 'React'], 124 | age: 20, 125 | isLoggedIn: false, 126 | points: 40 127 | }, 128 | Paul: { 129 | email: 'paul@paul.com', 130 | skills: ['HTML', 'CSS', 'JavaScript', 'MongoDB', 'Express', 'React', 'Node'], 131 | age: 20, 132 | isLoggedIn: false, 133 | points: 40 134 | } 135 | }; 136 | var loggedIn = 0; 137 | var points50 = 0; 138 | for (var _i = 0, _a = Object.keys(users); _i < _a.length; _i++) { 139 | var username = _a[_i]; 140 | var userLoggedIn = users[username].isLoggedIn; 141 | var userPoints = users[username].points; 142 | console.log(username + ": " + userLoggedIn + ", " + userPoints); 143 | if (userLoggedIn) { 144 | loggedIn += 1; 145 | } 146 | if (userPoints >= 50) { 147 | points50 += 1; 148 | } 149 | } 150 | console.log("Logged in users: " + loggedIn + ", Points >= 50: " + points50); 151 | var copyUsers = Object.assign({}, users); 152 | copyUsers['Eugene'] = {}; 153 | copyUsers['Eugene']['email'] = 'eugene@eugeneyan.com'; 154 | copyUsers['Eugene']['skills'] = ['SQL', 'Python', 'Scala', 'TypeScript']; 155 | copyUsers['Eugene']['age'] = 34; 156 | copyUsers['Eugene']['isLoggedIn'] = true; 157 | copyUsers['Eugene']['points'] = 30; 158 | console.log(copyUsers); 159 | console.log(Object.keys(users)); 160 | console.log(Object.values(users)); 161 | console.log(Object.entries(users)); 162 | -------------------------------------------------------------------------------- /basics-i/day8/main.ts: -------------------------------------------------------------------------------- 1 | export { } 2 | 3 | let a = 'JavaScript' // Global scope 4 | let b = 10 // Global scope 5 | 6 | function letsLearnScope() { 7 | console.log(`The awesome of ${a} is ${b}`) 8 | 9 | let c = 30 10 | 11 | if (true) { 12 | let a = 'Python' // Local scope 13 | let b = 100 // Local scope 14 | console.log(`The awesome of ${a} is ${b}`) 15 | } 16 | 17 | console.log(`The awesome of ${a} is ${b}`) 18 | } 19 | 20 | letsLearnScope() 21 | console.log(`The awesome of ${a} is ${b}`) 22 | 23 | // var vs. let 24 | function letsLearnScope2() { 25 | var gravity = 9.81 26 | console.log(gravity) 27 | } 28 | 29 | // console.log(gravity) // This will fail with var or let 30 | 31 | if (true) { 32 | var gravity = 9.81 33 | console.log(gravity) 34 | } 35 | 36 | console.log(gravity) // This works with var and let, but VS code complains about let 37 | 38 | for (var i = 0; i < 3; i++) { 39 | console.log(`Loop: ${i}`) 40 | } 41 | 42 | console.log(i) 43 | 44 | // From ES6 and above, there's let and const. Suggest to only use let and const, and use const for 45 | // values which will will not change (like val for scala.) 46 | 47 | /* 48 | * Objects: Everything can be an object. Objects have properties and properties have values. 49 | * Thus, objects are key value pairs. The order of the key is not reserved. 50 | * To create objects, we use two curly brackets. 51 | */ 52 | 53 | const rectangle = { 54 | length: 20, 55 | width: 20 56 | } 57 | 58 | console.log(rectangle) 59 | 60 | const person = { 61 | firstName: 'Eugene', 62 | lastName: 'Yan', 63 | age: 34, 64 | country: 'United States', 65 | city: 'Seattle', 66 | skills: [ 67 | 'SQL', 68 | 'Python', 69 | 'Scala', 70 | 'TypeScript', 71 | 'Docker' 72 | ], 73 | isMarried: true, 74 | 'two word key': true, 75 | getFullName: function () { 76 | return `Full name is ${this.firstName} ${this.lastName}` // this is like python's self 77 | } 78 | } 79 | 80 | console.log(person) 81 | 82 | // Accessing values from objects 83 | console.log(person.firstName) 84 | console.log(person['firstName']) 85 | 86 | console.log(person['two word key']) // If the key is two words 87 | console.log(person.getFullName()) 88 | 89 | // Adding new keys 90 | person['nationality'] = 'Singaporean' // Though VS Code complains about this, it works 91 | person.skills.push('Spark') 92 | 93 | console.log(person['nationality']) 94 | 95 | // Object.assign: To copy object without modifying the original object 96 | const copyperson = Object.assign({}, person) 97 | console.log(copyperson) 98 | 99 | const personKeys = Object.keys(person) 100 | console.log(personKeys) 101 | 102 | const personValues = Object.values(person) 103 | console.log(personValues) 104 | 105 | const personEntries = Object.entries(person) 106 | console.log(personEntries) 107 | 108 | console.log(person.hasOwnProperty('firstName')) 109 | console.log(person.hasOwnProperty('middleName')) 110 | 111 | 112 | // Exercises Level 2 113 | const users = { 114 | Alex: { 115 | email: 'alex@alex.com', 116 | skills: ['HTML', 'CSS', 'JavaScript'], 117 | age: 20, 118 | isLoggedIn: false, 119 | points: 30 120 | }, 121 | Asab: { 122 | email: 'asab@asab.com', 123 | skills: ['HTML', 'CSS', 'JavaScript', 'Redux', 'MongoDB', 'Express', 'React', 'Node'], 124 | age: 25, 125 | isLoggedIn: false, 126 | points: 50 127 | }, 128 | Brook: { 129 | email: 'daniel@daniel.com', 130 | skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux'], 131 | age: 30, 132 | isLoggedIn: true, 133 | points: 50 134 | }, 135 | Daniel: { 136 | email: 'daniel@alex.com', 137 | skills: ['HTML', 'CSS', 'JavaScript', 'Python'], 138 | age: 20, 139 | isLoggedIn: false, 140 | points: 40 141 | }, 142 | John: { 143 | email: 'john@john.com', 144 | skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux', 'Node.js'], 145 | age: 20, 146 | isLoggedIn: true, 147 | points: 50 148 | }, 149 | Thomas: { 150 | email: 'thomas@thomas.com', 151 | skills: ['HTML', 'CSS', 'JavaScript', 'React'], 152 | age: 20, 153 | isLoggedIn: false, 154 | points: 40 155 | }, 156 | Paul: { 157 | email: 'paul@paul.com', 158 | skills: ['HTML', 'CSS', 'JavaScript', 'MongoDB', 'Express', 'React', 'Node'], 159 | age: 20, 160 | isLoggedIn: false, 161 | points: 40 162 | } 163 | } 164 | 165 | let loggedIn = 0 166 | let points50 = 0 167 | 168 | for (const username of Object.keys(users)) { 169 | let userLoggedIn = users[username].isLoggedIn 170 | let userPoints = users[username].points 171 | console.log(`${username}: ${userLoggedIn}, ${userPoints}`) 172 | 173 | if (userLoggedIn) { 174 | loggedIn += 1 175 | } 176 | 177 | if (userPoints >= 50) { 178 | points50 += 1 179 | } 180 | } 181 | 182 | console.log(`Logged in users: ${loggedIn}, Points >= 50: ${points50}`) 183 | 184 | const copyUsers = Object.assign({}, users) 185 | 186 | copyUsers['Eugene'] = { } 187 | copyUsers['Eugene']['email'] = 'eugene@eugeneyan.com' 188 | copyUsers['Eugene']['skills'] = ['SQL', 'Python', 'Scala', 'TypeScript'] 189 | copyUsers['Eugene']['age'] = 34 190 | copyUsers['Eugene']['isLoggedIn'] = true 191 | copyUsers['Eugene']['points'] = 30 192 | 193 | console.log(copyUsers) 194 | 195 | console.log(Object.keys(users)) 196 | console.log(Object.values(users)) 197 | console.log(Object.entries(users)) -------------------------------------------------------------------------------- /basics-i/day11/main.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var __assign = (this && this.__assign) || function () { 3 | __assign = Object.assign || function(t) { 4 | for (var s, i = 1, n = arguments.length; i < n; i++) { 5 | s = arguments[i]; 6 | for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) 7 | t[p] = s[p]; 8 | } 9 | return t; 10 | }; 11 | return __assign.apply(this, arguments); 12 | }; 13 | var __read = (this && this.__read) || function (o, n) { 14 | var m = typeof Symbol === "function" && o[Symbol.iterator]; 15 | if (!m) return o; 16 | var i = m.call(o), r, ar = [], e; 17 | try { 18 | while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); 19 | } 20 | catch (error) { e = { error: error }; } 21 | finally { 22 | try { 23 | if (r && !r.done && (m = i["return"])) m.call(i); 24 | } 25 | finally { if (e) throw e.error; } 26 | } 27 | return ar; 28 | }; 29 | var __values = (this && this.__values) || function(o) { 30 | var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; 31 | if (m) return m.call(o); 32 | if (o && typeof o.length === "number") return { 33 | next: function () { 34 | if (o && i >= o.length) o = void 0; 35 | return { value: o && o[i++], done: !o }; 36 | } 37 | }; 38 | throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); 39 | }; 40 | var __spread = (this && this.__spread) || function () { 41 | for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); 42 | return ar; 43 | }; 44 | var e_1, _a, e_2, _b; 45 | exports.__esModule = true; 46 | // Destructing is a way to unpack arrays and assign them to a distinct variable 47 | var numbers = [1, 2, 3]; 48 | var _c = __read(numbers, 3), one = _c[0], two = _c[1], three = _c[2]; 49 | console.log(one, two, three); 50 | // To sip values on values in the array just use an additional comma 51 | var _d = __read(numbers, 3), numOne = _d[0], numThree = _d[2]; 52 | console.log(numOne, numThree); 53 | var names = [undefined, 'A', 'B']; 54 | var _e = __read(names, 4), _f = _e[0], first = _f === void 0 ? 'First' : _f, second = _e[1], third = _e[2], _g = _e[3], forth = _g === void 0 ? 'Forth' : _g; 55 | console.log(first, second, third, forth); 56 | // We can use the spread operator (...) to assign the remaining 57 | var nums = [1, 2, 3, 4, 5, 6, 7, 8]; 58 | var _h = __read(nums), num1 = _h[0], num2 = _h[1], num3 = _h[2], rest = _h.slice(3); 59 | console.log(num1, num2, num3); 60 | console.log(rest); 61 | // We can also destructure via iteration 62 | var countries = [['Finland', 'Helsinki'], ['Sweden', 'Stockholm'], ['Norway', 'Oslo']]; 63 | try { 64 | for (var countries_1 = __values(countries), countries_1_1 = countries_1.next(); !countries_1_1.done; countries_1_1 = countries_1.next()) { 65 | var _j = __read(countries_1_1.value, 2), country = _j[0], city = _j[1]; 66 | console.log(country, city); 67 | } 68 | } 69 | catch (e_1_1) { e_1 = { error: e_1_1 }; } 70 | finally { 71 | try { 72 | if (countries_1_1 && !countries_1_1.done && (_a = countries_1["return"])) _a.call(countries_1); 73 | } 74 | finally { if (e_1) throw e_1.error; } 75 | } 76 | // When destructuring objects, the name of variable should be exactly the same as object keys 77 | // Destructuring is done using { } 78 | var rect = { 79 | width: 20, 80 | height: 10, 81 | area: 200 82 | }; 83 | var width = rect.width, height = rect.height, area = rect.area, perimeter = rect.perimeter; 84 | console.log(width, height, area, perimeter); // perimeter will be undefined 85 | // You can also rename when restructuring 86 | var w = rect.width, h = rect.height, a = rect.area, p = rect.perimeter; 87 | console.log(w, h, a, p); 88 | var rect2 = { 89 | width2: 20, 90 | height2: 10, 91 | area2: 200 92 | }; 93 | // Assigning it to a defaault value 94 | var _k = rect2.width2, width2 = _k === void 0 ? 1 : _k, height2 = rect2.height2, area2 = rect2.area2, _l = rect2.perimeter2, perimeter2 = _l === void 0 ? 60 : _l; 95 | console.log(width2, height2, area2, perimeter2); // perimeter will be 60, width2 will not be updated 96 | // Getting object parameters without destructuring 97 | var calcPerimeter = function (rect) { 98 | return 2 * (rect.width + rect.height); 99 | }; 100 | console.log(calcPerimeter(rect)); 101 | // Getting object parameters with destructuring 102 | var calculatePerimeter = function (_a) { 103 | var width = _a.width, height = _a.height; 104 | return 2 * (width + height); 105 | }; 106 | console.log(calculatePerimeter(rect)); 107 | // Destructuring object during iteration 108 | var todoList = [ 109 | { 110 | task: 'Prepare JS Test', 111 | time: '4/1/2020 8:30', 112 | completed: true 113 | }, 114 | { 115 | task: 'Give JS Test', 116 | time: '4/1/2020 10:00', 117 | completed: false 118 | }, 119 | { 120 | task: 'Assess Test Result', 121 | time: '4/1/2020 1:00', 122 | completed: false 123 | } 124 | ]; 125 | try { 126 | for (var todoList_1 = __values(todoList), todoList_1_1 = todoList_1.next(); !todoList_1_1.done; todoList_1_1 = todoList_1.next()) { 127 | var _m = todoList_1_1.value, task = _m.task, time = _m.time, completed = _m.completed; 128 | console.log(task, time, completed); 129 | } 130 | } 131 | catch (e_2_1) { e_2 = { error: e_2_1 }; } 132 | finally { 133 | try { 134 | if (todoList_1_1 && !todoList_1_1.done && (_b = todoList_1["return"])) _b.call(todoList_1); 135 | } 136 | finally { if (e_2) throw e_2.error; } 137 | } 138 | // The spread operator can be used to copy array 139 | var evens = [0, 2, 4, 6, 8, 10]; 140 | var odds = [1, 3, 5, 7, 9]; 141 | var evensCopy = __spread(evens); 142 | var oddsCopy = __spread(odds); 143 | var allCopy = __spread(evens, odds); 144 | console.log(evensCopy); 145 | console.log(oddsCopy); 146 | console.log(allCopy); 147 | // Spread can also be used to copy objects 148 | var rectCopy = __assign({}, rect); 149 | console.log(rectCopy); 150 | // We can modify objects while copying 151 | var rectCopy2 = __assign(__assign({}, rect), { width: 15 }); 152 | console.log(rectCopy2); 153 | // We can write arrow functions which take an unlimited amount of arguments using a spreaad operator 154 | var sumAllNums = function () { 155 | var e_3, _a; 156 | var args = []; 157 | for (var _i = 0; _i < arguments.length; _i++) { 158 | args[_i] = arguments[_i]; 159 | } 160 | console.log(args); 161 | var sum = 0; 162 | try { 163 | for (var args_1 = __values(args), args_1_1 = args_1.next(); !args_1_1.done; args_1_1 = args_1.next()) { 164 | var num = args_1_1.value; 165 | sum += num; 166 | } 167 | } 168 | catch (e_3_1) { e_3 = { error: e_3_1 }; } 169 | finally { 170 | try { 171 | if (args_1_1 && !args_1_1.done && (_a = args_1["return"])) _a.call(args_1); 172 | } 173 | finally { if (e_3) throw e_3.error; } 174 | } 175 | return sum; 176 | }; 177 | console.log(sumAllNums(1, 2, 3, 4, 5)); 178 | -------------------------------------------------------------------------------- /basics-i/day15/main.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Classes are object constructors that we can instantiate to create an object (from week 8). 3 | */ 4 | var __extends = (this && this.__extends) || (function () { 5 | var extendStatics = function (d, b) { 6 | extendStatics = Object.setPrototypeOf || 7 | ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || 8 | function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; 9 | return extendStatics(d, b); 10 | }; 11 | return function (d, b) { 12 | extendStatics(d, b); 13 | function __() { this.constructor = d; } 14 | d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); 15 | }; 16 | })(); 17 | // Instatiating a class: To create an object from a class 18 | var Person = /** @class */ (function () { 19 | function Person() { 20 | } 21 | return Person; 22 | }()); 23 | var person = new Person(); 24 | console.log(person); 25 | /* 26 | * Constructor is a builtin function to create a blueprint for objects 27 | * use this keyword to attach constructor parameters into the class 28 | */ 29 | var Person2 = /** @class */ (function () { 30 | function Person2(firstName, lastName) { 31 | console.log(this); 32 | this.firstName = firstName; 33 | this.lastName = lastName; 34 | } 35 | return Person2; 36 | }()); 37 | var person2 = new Person2('Eugene', 'Yan'); 38 | console.log(person2); 39 | // Add default values 40 | var Person3 = /** @class */ (function () { 41 | function Person3(firstName, lastName) { 42 | if (firstName === void 0) { firstName = 'John'; } 43 | if (lastName === void 0) { lastName = 'Doe'; } 44 | this.firstName = firstName; 45 | this.lastName = lastName; 46 | } 47 | return Person3; 48 | }()); 49 | var person3 = new Person3(); 50 | console.log(person3); 51 | // Adding class methods 52 | var Person4 = /** @class */ (function () { 53 | function Person4(firstName, lastName) { 54 | if (firstName === void 0) { firstName = 'John'; } 55 | if (lastName === void 0) { lastName = 'Doe'; } 56 | this.firstName = firstName; 57 | this.lastName = lastName; 58 | } 59 | Person4.prototype.getFullName = function () { 60 | var fullName = this.firstName + " " + this.lastName; 61 | return fullName; 62 | }; 63 | return Person4; 64 | }()); 65 | var person4 = new Person4(); 66 | console.log(person4.getFullName()); 67 | // Getters and setters 68 | var Person5 = /** @class */ (function () { 69 | function Person5(firstName, lastName) { 70 | if (firstName === void 0) { firstName = 'John'; } 71 | if (lastName === void 0) { lastName = 'Doe'; } 72 | this.firstName = firstName; 73 | this.lastName = lastName; 74 | this.score = 0; 75 | this.skills = []; 76 | } 77 | Object.defineProperty(Person5.prototype, "getFullName", { 78 | get: function () { 79 | var fullName = this.firstName + " " + this.lastName; 80 | return fullName; 81 | }, 82 | enumerable: false, 83 | configurable: true 84 | }); 85 | Object.defineProperty(Person5.prototype, "getScore", { 86 | get: function () { 87 | return this.score; 88 | }, 89 | enumerable: false, 90 | configurable: true 91 | }); 92 | Object.defineProperty(Person5.prototype, "getSkills", { 93 | get: function () { 94 | return this.skills; 95 | }, 96 | enumerable: false, 97 | configurable: true 98 | }); 99 | Object.defineProperty(Person5.prototype, "setScore", { 100 | set: function (score) { 101 | this.score += score; 102 | }, 103 | enumerable: false, 104 | configurable: true 105 | }); 106 | Object.defineProperty(Person5.prototype, "setSkill", { 107 | set: function (skill) { 108 | this.skills.push(skill); 109 | }, 110 | enumerable: false, 111 | configurable: true 112 | }); 113 | return Person5; 114 | }()); 115 | var person5 = new Person5(); 116 | console.log(person5.getFullName); // No () when calling getter 117 | console.log(person5.getScore); 118 | console.log(person5.getSkills); 119 | person5.setScore = 1; 120 | person5.setSkill = 'Python'; 121 | person5.setSkill = 'Scala'; 122 | person5.setSkill = 'TypeScript'; 123 | console.log(person5.getScore); 124 | console.log(person5.getSkills); 125 | // Static methods: Not called on instances of the class, but the class itself. 126 | // They're often utility functions, and are called directly from the class 127 | var Person6 = /** @class */ (function () { 128 | function Person6(firstName, lastName) { 129 | if (firstName === void 0) { firstName = 'John'; } 130 | if (lastName === void 0) { lastName = 'Doe'; } 131 | this.firstName = firstName; 132 | this.lastName = lastName; 133 | this.score = 0; 134 | this.skills = []; 135 | } 136 | Person6.showDateTime = function () { 137 | var now = new Date(); 138 | var year = now.getFullYear(); 139 | var month = now.getMonth() + 1; 140 | var date = now.getDate(); 141 | var fullDate = year + "-" + month + "-" + date; 142 | return fullDate; 143 | }; 144 | return Person6; 145 | }()); 146 | console.log(Person6.showDateTime()); 147 | // Inheritance: Child class can access all properties of parent class, reducing code repetition 148 | var Student = /** @class */ (function (_super) { 149 | __extends(Student, _super); 150 | function Student() { 151 | return _super !== null && _super.apply(this, arguments) || this; 152 | } 153 | Student.prototype.saySomething = function () { 154 | console.log('I am a child of Person5'); // Not sure why this causes undefined in log 155 | }; 156 | return Student; 157 | }(Person5)); 158 | var student = new Student(); 159 | console.log(student); 160 | console.log(student.saySomething()); 161 | console.log(student.getFullName); 162 | // Overriding methods: If we want to add properties, we'll need to use the constructor function 163 | // in the child class too. We can thes call super() to access all properties from the parent class. 164 | var Student2 = /** @class */ (function (_super) { 165 | __extends(Student2, _super); 166 | function Student2(firstName, lastName, gender) { 167 | var _this = _super.call(this, firstName, lastName) || this; 168 | _this.gender = gender; 169 | return _this; 170 | } 171 | Student2.prototype.saySomething = function () { 172 | console.log('I am a child of Person5'); // Not sure why this causes undefined in log 173 | }; 174 | Object.defineProperty(Student2.prototype, "getFullNameWithGender", { 175 | get: function () { 176 | var fullName = this.getFullName; 177 | var fullNameWithGender = fullName + " (gender: " + this.gender + ")"; 178 | return fullNameWithGender; 179 | }, 180 | enumerable: false, 181 | configurable: true 182 | }); 183 | return Student2; 184 | }(Person5)); 185 | var student2 = new Student2('Eugene', 'Yan', 'M'); 186 | console.log(student2.getFullNameWithGender); 187 | -------------------------------------------------------------------------------- /basics-i/day18/main.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { 3 | function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } 4 | return new (P || (P = Promise))(function (resolve, reject) { 5 | function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } 6 | function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } 7 | function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } 8 | step((generator = generator.apply(thisArg, _arguments || [])).next()); 9 | }); 10 | }; 11 | var __generator = (this && this.__generator) || function (thisArg, body) { 12 | var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; 13 | return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; 14 | function verb(n) { return function (v) { return step([n, v]); }; } 15 | function step(op) { 16 | if (f) throw new TypeError("Generator is already executing."); 17 | while (_) try { 18 | if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; 19 | if (y = 0, t) op = [op[0] & 2, t.value]; 20 | switch (op[0]) { 21 | case 0: case 1: t = op; break; 22 | case 4: _.label++; return { value: op[1], done: false }; 23 | case 5: _.label++; y = op[1]; op = [0]; continue; 24 | case 7: op = _.ops.pop(); _.trys.pop(); continue; 25 | default: 26 | if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } 27 | if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } 28 | if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } 29 | if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } 30 | if (t[2]) _.ops.pop(); 31 | _.trys.pop(); continue; 32 | } 33 | op = body.call(thisArg, _); 34 | } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } 35 | if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; 36 | } 37 | }; 38 | exports.__esModule = true; 39 | /* 40 | * Callbacks take two parameters. The first is err and the second is result. If err is false, there 41 | * will not be an error; otherwise, error. 42 | * 43 | * Callbacks are functions passed as an argument to another function. They are executed after 44 | * another function has finished executing, thus the name "callback" 45 | * - https://www.w3schools.com/js/js_callback.asp 46 | * - https://codeburst.io/javascript-what-the-heck-is-a-callback-aba4da2deced 47 | */ 48 | var doSomething = function (callback) { 49 | setTimeout(function () { 50 | var skills = ['Python', 'Scala', 'TypeScript']; 51 | callback('It did not go well', skills); 52 | }, 0); 53 | }; 54 | var callback = function (err, result) { 55 | if (err) { 56 | return console.log(err); 57 | } 58 | return console.log(result); 59 | }; 60 | // Prints after 0.3 secs 61 | doSomething(callback); 62 | // Change callback err arg to false 63 | var doSomething2 = function (callback) { 64 | setTimeout(function () { 65 | var skills = ['Python', 'Scala', 'TypeScript']; 66 | callback(false, skills); 67 | }, 0); 68 | }; 69 | // Prints after 0.2 secs, thus BEFORE the prior doSomething() is ran 70 | doSomething2(callback); 71 | /* 72 | * Promise: A way to handle async operations in JavaScript, allowing handlers with an async 73 | * action to have an eventual success value or failure reason. Instead of immediately returning 74 | * the final value, the async method returns a promise to supply the value sometime in the future. 75 | * 76 | * Promises have these states: 77 | * - pending: Initial state, neither fulfiled nor rejected 78 | * - fulfiled: Operation completed successfully 79 | * - rejected: Operation failed 80 | */ 81 | /* 82 | * Promises are created using the Promise constructor. Inside the constructor, it takes a 83 | * callback function, which has two parameters which are the resolve and reject functions. 84 | * - resolve: returns the result 85 | * - reject: returns as error in try catch 86 | */ 87 | var doPromise = new Promise(function (resolve, reject) { 88 | setTimeout(function () { 89 | var skills = ['Python', 'Scala', 'TypeScript', 'SQL']; 90 | if (skills.length > 0) { 91 | resolve(skills); 92 | } 93 | else { 94 | reject('Something wrong has happened'); 95 | } 96 | }, 0); 97 | }); 98 | // Settled with resolve 99 | doPromise 100 | .then(function (result) { 101 | console.log(result); 102 | })["catch"](function (error) { return console.log(error); }); 103 | var doPromise2 = new Promise(function (resolve, reject) { 104 | setTimeout(function () { 105 | var skills = ['Python', 'Scala', 'TypeScript', 'SQL']; 106 | if (skills.indexOf('Node') !== -1) { 107 | resolve('Fullstack dev'); 108 | } 109 | else { 110 | reject('Something wrong has happened'); 111 | } 112 | }, 0); 113 | }); 114 | // Settled with reject 115 | doPromise2 116 | .then(function (result) { 117 | console.log(result); 118 | })["catch"](function (error) { return console.log(error); }); 119 | var fetch = require('node-fetch'); 120 | var url = 'https://restcountries.eu/rest/v2/all'; 121 | // fetch(url) // Where does response come from? 122 | // .then(response => response.json()) // Access API data as JSON 123 | // .then(data => { 124 | // console.log(data) 125 | // }) 126 | // .catch(error => console.log(error)) 127 | /* 128 | * Async and Await: An elegant way to handle promises. 129 | * - async: Having it infront of a function means the function will return a promise 130 | * - await: to access the value from the promise 131 | */ 132 | var square = function (n) { 133 | return __awaiter(this, void 0, void 0, function () { 134 | return __generator(this, function (_a) { 135 | return [2 /*return*/, n * n]; 136 | }); 137 | }); 138 | }; 139 | console.log(square(2)); 140 | var fetchData = function () { return __awaiter(void 0, void 0, void 0, function () { 141 | var response, countries, err_1; 142 | return __generator(this, function (_a) { 143 | switch (_a.label) { 144 | case 0: 145 | _a.trys.push([0, 3, , 4]); 146 | return [4 /*yield*/, fetch(url)]; 147 | case 1: 148 | response = _a.sent(); 149 | return [4 /*yield*/, response.json()]; 150 | case 2: 151 | countries = _a.sent(); 152 | console.log(countries); 153 | return [3 /*break*/, 4]; 154 | case 3: 155 | err_1 = _a.sent(); 156 | console.log(err_1); 157 | return [3 /*break*/, 4]; 158 | case 4: return [2 /*return*/]; 159 | } 160 | }); 161 | }); }; 162 | console.log('===== async and await'); 163 | fetchData(); 164 | --------------------------------------------------------------------------------