├── 001-Basics
├── 001-hello.js
├── 002-conditionals.js
├── 003-loops.js
├── 004-functions.js
├── 005-strings.js
├── 006-stringMethods.js
└── 007-stringSearchMethods.js
├── 002-Arrays
├── 001-arrays.js
├── 002-arrayMethods.js
├── 003-arraySearchMethods.js
├── 004-arraySortMethods.js
├── 005-rapidCodeRound.js
└── 006-IterationMethods
│ ├── 001-for-of.js
│ ├── 002-for-in.js
│ ├── 003-forEach.js
│ ├── 004-map.js
│ ├── 005-flatMap.js
│ ├── 006-filter.js
│ ├── 007-reduce.js
│ ├── 008-reduceRight.js
│ ├── 009-every.js
│ ├── 010-some.js
│ ├── 011-from.js
│ ├── 012-keys.js
│ ├── 013-entries.js
│ ├── 014-with.js
│ └── 015-spread.js
├── 003-Objects
├── 001-objects.js
├── 002-memory.js
├── 003-rapidCodeRound.js
├── 004-generalObjectMethods.js
├── 005-propertyManagementMethods.js
└── 006-objectProtectionMethods.js
├── 004-Polyfills
├── PolyfillsForMethods-MachineCoding
│ ├── 001-forEach.js
│ ├── 002-map.js
│ ├── 003-filter.js
│ ├── 004-reduce.js
│ └── 005-promise.js
└── pollyfillsBasics.js
├── 005-ObjectsAndClasses
├── 001-basics.js
└── 002-class.js
├── 006-DOM
├── 001-Basics
│ ├── External JS
│ │ ├── index.html
│ │ └── index.js
│ └── index.html
├── 002-Example
│ ├── index.html
│ └── index.js
└── 003-EventListeners
│ ├── 001-ButtonExample
│ ├── index.html
│ └── index.js
│ └── 002-BasicTodoExample
│ ├── README.md
│ ├── index.html
│ ├── index.js
│ └── wireframe.png
├── 007-SpeedJS
├── 001-dataTypes.js
├── 002-arrayAndObjects.js
├── 003-controlFlow.js
├── 004-iteration.js
└── 005-functions.js
├── 008-MachineCoding
├── ArrayMethods
│ └── iteration.js
└── Polyfills
│ ├── 001-forEach.js
│ ├── 002-map.js
│ ├── 003-filter.js
│ ├── 004-reduce.js
│ └── 005-promise.js
├── 009-Proxy
├── 001-proxy.js
└── 002-negativeIndexExample.js
├── 010-ClockProject
├── index.html
├── script.js
└── style.css
├── 011-Promise
├── 001-Basics
│ ├── index.html
│ └── script.js
├── 002-PromiseChaining
│ ├── index.html
│ └── script.js
└── 003-CleanCode
│ ├── index.html
│ └── script.js
├── 012-Sync-Async-JS
├── 001-syncCode.js
├── 002-asyncCode.js
├── 003-sumSync.js
├── 004-sumAsync.js
├── 005-callbackHell.js
├── 006-fs-promises.js
├── 007-promisification.js
├── 008-async-await.js
└── 009-assignment.js
├── 013-LexicalScoping-ClosureFunctions
├── 001-lexicalScope-closureFunction.js
├── 002-counter.js
└── 003-memoryLeak-Closure.js
├── 014-Debouncing
├── debounce.js
└── debounce.md
├── 015-Throttling
├── throttling.js
└── throttling.md
├── 016-CodeChallenges
├── 001-P0
│ ├── p0-challenge-01.js
│ ├── p0-challenge-02.js
│ └── p0-challenge-03.js
├── 002-Conditionals
│ ├── challenge-01.js
│ ├── challenge-02.js
│ ├── challenge-03.js
│ ├── challenge-04.js
│ ├── challenge-05.js
│ ├── challenge-06.js
│ ├── challenge-07.js
│ ├── challenge-08.js
│ ├── challenge-09.js
│ └── challenge-10.js
├── 003-Loops
│ ├── challenge-01.js
│ ├── challenge-02.js
│ ├── challenge-03.js
│ ├── challenge-04.js
│ ├── challenge-05.js
│ ├── challenge-06.js
│ ├── challenge-07.js
│ ├── challenge-08.js
│ ├── challenge-09.js
│ └── challenge-10.js
├── 004-Arrays
│ ├── challenge-01.js
│ ├── challenge-02.js
│ ├── challenge-03.js
│ ├── challenge-04.js
│ ├── challenge-05.js
│ ├── challenge-06.js
│ ├── challenge-07.js
│ ├── challenge-08.js
│ ├── challenge-09.js
│ └── challenge-10.js
├── 005-Prototypes
│ ├── challenge-01.js
│ ├── challenge-02.js
│ ├── challenge-03.js
│ ├── challenge-04.js
│ ├── challenge-05.js
│ ├── challenge-06.js
│ ├── challenge-07.js
│ ├── challenge-08.js
│ ├── challenge-09.js
│ └── challenge-10.js
└── 006-Objects
│ ├── challenge-01.js
│ ├── challenge-02.js
│ ├── challenge-03.js
│ ├── challenge-04.js
│ ├── challenge-05.js
│ ├── challenge-06.js
│ ├── challenge-07.js
│ ├── challenge-08.js
│ ├── challenge-09.js
│ └── challenge-10.js
├── 017-Practice
├── 001-JS-Basics
│ ├── README.md
│ ├── exercise-1a.js
│ ├── exercise-1b.js
│ ├── exercise-1c.js
│ ├── exercise-1d.js
│ ├── exercise-1e.js
│ ├── exercise-1f.js
│ ├── exercise-1g.js
│ ├── exercise-1h.js
│ ├── exercise-1i.js
│ └── exercise-1j.js
├── 002-Numbers-Maths
│ ├── README.md
│ ├── exercise-2a.js
│ ├── exercise-2b.js
│ ├── exercise-2c.js
│ ├── exercise-2d.js
│ ├── exercise-2e.js
│ ├── exercise-2f.js
│ ├── exercise-2g.js
│ ├── exercise-2h.js
│ ├── exercise-2i.js
│ ├── exercise-2j.js
│ ├── exercise-2k.js
│ ├── exercise-2l.js
│ ├── exercise-2m.js
│ └── exercise-2n.js
├── 003-Strings
│ ├── README.md
│ ├── exercise-3a.js
│ ├── exercise-3b.js
│ ├── exercise-3c.js
│ ├── exercise-3d.js
│ ├── exercise-3e.js
│ ├── exercise-3f.js
│ ├── exercise-3g.js
│ ├── exercise-3h.js
│ ├── exercise-3i.js
│ ├── exercise-3j.js
│ ├── exercise-3k.js
│ ├── exercise-3l.js
│ ├── exercise-3m.js
│ └── exercise-3n.js
├── 004-console-log
│ ├── README.md
│ └── exercise-4.html
├── 005-Variables
│ ├── README.md
│ └── exercise.html
├── 006-Booleans-IfStatements
│ ├── README.md
│ └── rock-paper-scissors.html
├── 007-Functions
│ ├── calculator.html
│ └── rock-paper-scissors.html
├── 008-Objects
│ ├── calculator.html
│ └── rock-paper-scissors.html
├── 009-DOM
│ ├── Exercises
│ │ ├── exercise-9a.html
│ │ ├── exercise-9b.html
│ │ ├── exercise-9c.html
│ │ ├── exercise-9d.html
│ │ ├── exercise-9e.html
│ │ ├── exercise-9g.html
│ │ └── exercise-9h.html
│ ├── Projects
│ │ ├── amazon-shipping-calc.html
│ │ ├── calculator.html
│ │ ├── rock-paper-scisssors.html
│ │ └── youtube-subscribe.html
│ └── dom.html
├── 010-DOMWithCSS
│ ├── 001-SubscribeButton
│ │ ├── index.html
│ │ ├── script.js
│ │ └── style.css
│ ├── 002-RockPaperScissors
│ │ ├── README.md
│ │ ├── images
│ │ │ ├── paper-emoji.png
│ │ │ ├── rock-emoji.png
│ │ │ └── scissors-emoji.png
│ │ ├── index.html
│ │ ├── script.js
│ │ └── style.css
│ └── 003-Calculator
│ │ ├── index.html
│ │ ├── script.js
│ │ └── style.css
├── 011-ArraysAndLoops
│ ├── Exercises
│ │ └── exercise.js
│ └── TodoList
│ │ ├── index.html
│ │ ├── script.js
│ │ └── style.css
└── 012-AdvancedFunctions
│ ├── 12a.js
│ ├── 12b.js
│ ├── 12c.html
│ ├── 12c.js
│ ├── 12d.html
│ ├── 12d.js
│ ├── 12e.html
│ ├── 12e.js
│ ├── 12f.html
│ ├── 12f.js
│ ├── 12g.html
│ ├── 12g.js
│ ├── 12h.html
│ ├── 12h.js
│ ├── 12i.html
│ ├── 12i.js
│ ├── 12j.js
│ ├── 12k.js
│ ├── 12l.js
│ ├── 12m.js
│ ├── 12n.js
│ ├── 12o.js
│ └── README.md
├── 018-Projects
├── 001-Clock
│ ├── index.html
│ ├── script.js
│ └── style.css
├── 002-CountdownTimer
│ ├── README.md
│ ├── index.html
│ └── script.js
├── 003-RandomQuoteGenerator
│ ├── index.html
│ ├── script.js
│ └── style.css
└── 004-TodoList
│ ├── index.html
│ ├── script.js
│ └── style.css
├── README.md
└── Warmup
├── 002Feb08th.js
├── 002Feb09th.js
└── 002Feb12th.js
/001-Basics/001-hello.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | Primitive:
4 | - String
5 | - Numbers
6 | - Integer
7 | - Float
8 | - Boolean
9 | - Null
10 | - Undefined
11 | - Symbol
12 | - BigInt
13 |
14 | Non-Primitive
15 | - Array []
16 | - Object {}
17 |
18 | Declaration
19 | - let
20 | - const
21 | - var
22 | */
23 |
24 | function printChai(n){
25 | console.log("Hello Chai", n);
26 | console.log("Hello,", n, "Chai");
27 | }
28 |
29 | function printCoffee(n){
30 | console.log(`Hello ${n} Coffee`);
31 | }
32 |
33 | function addTwo(a, b){
34 | console.log(a+b);
35 | }
36 |
37 | function mutliplyTwo(a, b){
38 | return a*b;
39 | }
40 |
41 | printChai(4);
42 | printCoffee(10);
43 | addTwo(10, 20);
44 | mutliplyTwo(10*20);
45 | console.log(mutliplyTwo(10, 40));
46 |
--------------------------------------------------------------------------------
/001-Basics/002-conditionals.js:
--------------------------------------------------------------------------------
1 | let weather = "rainy";
2 |
3 | /*
4 | == --> Checks if values are equal or not
5 | === --> Checks for value of equality and type of equality
6 | */
7 | if(weather === "rainy"){
8 | console.log("It's a rainy day");
9 | }else if(weather === "cloudy"){
10 | console.log("It's a cloudy day");
11 | }else{
12 | console.log("It's a sunny day");
13 | }
--------------------------------------------------------------------------------
/001-Basics/003-loops.js:
--------------------------------------------------------------------------------
1 | let cars = ["Mercedes", "BMW", "Audi", "Porsche"];
2 |
3 | for(let i = 0; i < cars.length; i++){
4 | console.log(cars[i]);
5 | }
--------------------------------------------------------------------------------
/001-Basics/005-strings.js:
--------------------------------------------------------------------------------
1 | let car1 = "Mercedes";
2 | let car2 = 'Bugatti';
3 | console.log(typeof car1);
4 | console.log(typeof car2);
5 |
6 | // Strings can also be defined as objects
7 | let car3 = new String("Land Rover");
8 | console.log(typeof car3);
9 |
10 | let str1 = "That is a 'car'";
11 | let str2 = 'That is a "car"';
12 |
13 | // Template String/ Template literal
14 | let numOfCars = 10;
15 | let str = `These
16 | are cars. They are
17 | amazingly fast. There are ${numOfCars} cars`;
18 |
19 | let myCar = "It\'s my car";
20 |
21 | const num = 5;
22 | // String Interpolation
23 | let numCars = `I have ${5} cars`;
24 |
25 | console.log(car1);
26 | console.log(car2);
27 | console.log(car3);
28 | console.log(str1);
29 | console.log(str2);
30 | console.log(str);
31 | console.log(myCar);
32 | console.log(numCars)
--------------------------------------------------------------------------------
/001-Basics/007-stringSearchMethods.js:
--------------------------------------------------------------------------------
1 | const bigStr = "Iron Man siad that, I am Iron Man, because his suit is made up of Iron";
2 |
3 | // indexOf() - index of first occurrence of beginning of the string
4 | const firstIndex = bigStr.indexOf("Iron");
5 | console.log(firstIndex);
6 |
7 | const firstIndexAfter = bigStr.indexOf("Iron", 10);
8 | console.log(firstIndexAfter);
9 |
10 | //lastIndexOf() - index of last occurrence of beginning of the string
11 | const lastIndex = bigStr.lastIndexOf("Iron");
12 | console.log(lastIndex);
13 |
14 | // search() - searches a string for a string (or a regular expression) and returns the position of the match. It cannot take second argument (where to begin search)
15 | const searchIndex = bigStr.search("Iron");
16 | console.log(searchIndex);
17 |
18 | const text = "The rain in SPAIN stays mainly in the plain";
19 |
20 | // match() - returns an array containing the results of matching a string against a string (or a regular expression)
21 | console.log(text.match("ain")); // Perform a search for "ain" (first occurrence)
22 | console.log(text.match(/ain/)); // Perform a search for "ain" (first occurrence)
23 | console.log(text.match(/ain/g)); // Perform a global search for "ain" (returns all occurrences)
24 | console.log(text.match(/ain/gi)); // Perform a global search for "ain" (returns all occurrences, case-insensitive)
25 |
26 | // matchAll() - returns an iterator containing the results of matching a string against a string (or a regular expression)
27 | console.log(text.matchAll("ain"));
28 |
29 | // includes()
30 | console.log(bigStr.includes("Hulk"));
31 | console.log(bigStr.includes("Iron Man"));
32 |
33 | // startsWith()
34 | console.log(bigStr.startsWith("Iron")); // true
35 | console.log(bigStr.startsWith("Man", 5)); // true
36 | console.log(bigStr.startsWith("Gold")); // false
37 |
38 | // endsWith()
39 | console.log(bigStr.endsWith("on")); // true
40 |
41 |
--------------------------------------------------------------------------------
/002-Arrays/001-arrays.js:
--------------------------------------------------------------------------------
1 | // Arrays
2 |
3 | let cars = ["Mercedes", "BMW", "Audi", "Porsche"];
4 | console.log(cars);
5 |
6 | let fruits = new Array("Apple", "Mango", "Grapes");
7 | console.log(fruits);
8 |
9 | // Objects
10 | let person = {
11 | firstName: "Tony",
12 | lastName: "Stark",
13 | age: 50
14 | };
15 | console.log(person);
16 |
17 |
18 | //Arrays are special type of objects
19 | console.log(typeof cars);
20 | console.log(typeof fruits);
21 | console.log(typeof person);
22 |
23 | // Array.isArray() is used to check if given element is an array
24 | console.log(Array.isArray(cars));
25 | console.log(Array.isArray(fruits));
26 | console.log(Array.isArray(person));
27 |
28 | // Converting array to string
29 | const fruitString = fruits.toString();
30 | console.log(fruitString);
31 |
32 | // Arrays are references
33 |
34 | const arr1 = [1, 2, 3];
35 | const arr2 = arr1;
36 |
37 | arr2.push(4);
38 | console.log(arr1); // [ 1, 2, 3, 4 ]
39 | console.log(arr2); // [ 1, 2, 3, 4 ]
40 |
41 | const arr3 = [1, 2, 3];
42 | const arr4 = arr3.slice();
43 |
44 | arr4.push(4);
45 | console.log(arr3); // [ 1, 2, 3]
46 | console.log(arr4); // [ 1, 2, 3, 4 ]
47 |
48 |
49 | // Destructuring
50 |
51 | const [fisrtValue, secondValue] = [1, 2, 3, 4];
52 |
53 | console.log(fisrtValue); // 1
54 | console.log(secondValue); // 2
--------------------------------------------------------------------------------
/002-Arrays/002-arrayMethods.js:
--------------------------------------------------------------------------------
1 | let cars = ["Mercedes", "BMW", "Audi", "Porsche"];
2 | let cars1 = ["Suzuki", "Hyundai", "Honda", "Mahindra", "Tata"];
3 | let cars2 = ["Rolls Royce", "Bugatti", "Lamborghini"];
4 |
5 | // length/ size of array
6 | console.log(cars.length);
7 |
8 | // convert array to string, and seperate elements using comma
9 | console.log(cars.toString());
10 |
11 | // convert array to string, and seperate elements using any seperator
12 | console.log(cars.join("*"));
13 |
14 | // element at specific index
15 | console.log(cars.at(1));
16 | console.log(cars[1]);
17 |
18 | // adding elements to the end of array
19 | console.log(cars.push("Land Rover"));
20 | console.log(cars);
21 | cars[cars.length] = "Lexus";
22 | console.log(cars);
23 |
24 | // removing last element from array
25 | console.log(cars.pop());
26 | console.log(cars);
27 |
28 | // shift() - removes first element from array and moves all other elements to lower index
29 | console.log(cars.shift());
30 | console.log(cars);
31 |
32 | // unshift() - add elements to the beginning of the array and moves other elements to higher index
33 | console.log(cars.unshift("Jaguar"));
34 | console.log(cars);
35 |
36 | // changing element at particular index
37 | cars[0] = "Opel";
38 | console.log(cars);
39 |
40 | // Concatenating arrays
41 | const allCars = cars.concat(cars1, cars2);
42 | console.log(allCars);
43 |
44 | // copy array element to another position
45 | cars.copyWithin(1, 4);
46 | console.log(cars);
47 |
48 | // reducing dimension of array
49 | let nums = [[1,2], [3,4], [5,6], [7,8]];
50 | console.log(nums);
51 |
52 | const newNums = nums.flat();
53 | console.log(newNums);
54 |
55 | // flatMap() - maps all elements of array, then creates new array by flattening the array
56 | let nums1 = [1,2,3,4,5];
57 | const mappedNums = nums1.flatMap(x => [x, x*10]);
58 | console.log(mappedNums);
59 |
60 | // splice() - adds new items to array
61 | let phones = ["iPhone", "Samsung", "Motoroala", "Xiaomi", "Asus", "Nothing"];
62 | let removedPhones = phones.splice(2, 0, "Oppo", "Vivo");
63 | console.log(removedPhones);
64 | console.log(phones);
65 | // Elements are spliced in at index 2
66 | // 0 elemts are removed
67 | // New array: ['iPhone','Samsung','Oppo','Vivo','Motoroala','Xiaomi','Asus','Nothing']
68 |
69 |
70 | removedPhones = phones.splice(3, 1, "OnePlus", "Realme", "Honor");
71 | console.log(removedPhones);
72 | console.log(phones);
73 | // Elements are spliced in at index 3
74 | // 1 elemts are removed (Vivo)
75 | // New array: ['iPhone','Samsung','Oppo','OnePlus','Realme','Honor','Motoroala','Xiaomi','Asus','Nothing']
76 |
77 | // toSpliced() - splice an array without altering original array (creates a new array)
78 | const newPhones = phones.toSpliced(1, 0, "Lenovo");
79 | console.log(newPhones);
80 |
81 |
82 | // slice() - slices out a pieceof array into new array
83 | let phones1 = phones.slice(1, 5);
84 | console.log(phones1);
85 | // Element at index 1 is included, element at index 5 is not included
--------------------------------------------------------------------------------
/002-Arrays/003-arraySearchMethods.js:
--------------------------------------------------------------------------------
1 | let cars = ["Mercedes", "BMW", "Audi", "Mercedes", "Land Rover", "Mercedes", "Jaguar", "Land Rover"];
2 | console.log(cars);
3 |
4 | // indexOf()
5 | console.log(cars.indexOf("Mercedes")); // First occurance of element
6 | console.log(cars.indexOf("Mercedes", 1)); // First occurance of element after specified index
7 | console.log(cars.indexOf("Tata")); // Returns -1, if element is not found
8 |
9 | // lastIndexOf()
10 | console.log(cars.lastIndexOf("BMW")); // Last occurance of element
11 |
12 | // includes()
13 | console.log(cars.includes("Land Rover")); // true
14 | console.log(cars.includes("Opel")); // false
15 |
16 | // find() - returns the value of the first array element that passes a test function
17 | // findIndex() - returns the index value of the first array element that passes a test function
18 | // findLast() - starts searching at end, and returns the first array element (from last) that passes a test function
19 | // findLastIndex() - starts searching at end, and returns the index of the first array element (from last) that passes a test function
20 |
21 | let found = cars.find((element) => element === "Land Rover" );
22 | let foundIndex = cars.findIndex((element) => element === "Land Rover");
23 |
24 | console.log(found);
25 | console.log(foundIndex);
26 |
27 | const nums = [5, 12, 8, 130, 44];
28 | found = nums.find((element) => element > 10);
29 | foundIndex = nums.findIndex((element) => element > 10);
30 | console.log(found);
31 | console.log(foundIndex);
32 |
33 | let foundLast = cars.findLast((element) => element === "Land Rover");
34 | let foundLastIndex = cars.findLastIndex((element) => element === "Land Rover");
35 | console.log(foundLast);
36 | console.log(foundLastIndex);
37 |
38 | foundLast = nums.findLast((element) => element > 10);
39 | foundLastIndex = nums.findLastIndex((element) => element > 10);
40 | console.log(foundLast);
41 | console.log(foundLastIndex);
42 |
43 |
44 |
--------------------------------------------------------------------------------
/002-Arrays/004-arraySortMethods.js:
--------------------------------------------------------------------------------
1 | let cars = ["Mercedes", "BMW", "Audi", "Mercedes", "Land Rover", "Mercedes", "Jaguar", "Land Rover"];
2 | console.log(cars);
3 |
4 | // reverse() - reverses the array
5 | cars.reverse();
6 | console.log(cars);
7 |
8 | // sort() - sorts the array alphabetically
9 | cars.sort();
10 | console.log(cars);
11 |
12 | let cars1 = ["Suzuki", "Hyundai", "Honda", "Mahindra", "Tata"];
13 | console.log(cars1);
14 |
15 | // toReversed() - reverses the array, without altering the original one
16 | const reversedCars1 = cars1.toReversed();
17 | console.log(reversedCars1);
18 |
19 | // toSorted() - sorts the array without altering the original one
20 | const sortedCars1 = cars1.toSorted();
21 | console.log(sortedCars1);
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/002-Arrays/005-rapidCodeRound.js:
--------------------------------------------------------------------------------
1 | // Problem: Create an array containing diff. types of teas
2 | const teas = ["Greean tea", "Black tea", "Oolong tea", "White tea", "Herbal tea"];
3 | console.log(teas);
4 |
5 | // Problem: Add "Chamomile tea" to the existing list of teas
6 | teas.push("Chamomile tea");
7 | console.log(teas);
8 |
9 | // Problem: Remove "Oolong tea" from the list of teas
10 | const index = teas.indexOf("Oolong Tea");
11 | if(index > -1){
12 | teas.splice(index, 1);
13 | }
14 |
15 | console.log(teas);
16 |
17 | // Problem: Filter the list to only include teas that are caffinated
18 | const caffinatedTeas = teas.filter((tea) => tea != "Herbal tea");
19 | console.log(caffinatedTeas);
20 |
21 | // Problem: Sort the list of teas in alphabetical order
22 | console.log(teas.sort());
23 |
24 | // Problem: Use a for loop to print each type of tea in array
25 | for(let i = 0; i < teas.length; i++){
26 | console.log(teas[i]);
27 | }
28 |
29 | // Problem: Use a for loop to count how many teas are caffinated (excluding "Herbal tea")
30 | let caffinatedCount = 0;
31 | for(let i = 0; i < teas.length; i++){
32 | if(teas != "Herabl tea"){
33 | caffinatedCount++;
34 | }
35 | }
36 | console.log(caffinatedCount);
37 |
38 | // Problem: Use a for loop to create a new array with all tea names in uppercase
39 | const upperCaseTeas = [];
40 | for(let i = 0; i < teas.length; i++){
41 | upperCaseTeas.push(teas[i].toUpperCase());
42 | }
43 | console.log(upperCaseTeas);
44 |
45 | // Problem: Use a for loop to find tea name with the most characters
46 | let longestTea = "";
47 |
48 | for(let i = 0; i < teas.length; i++){
49 | if(teas[i].length > longestTea.length){
50 | longestTea = teas[i];
51 | }
52 | }
53 |
54 | console.log(longestTea);
55 |
56 | // Problem: Use a for loop to reverse the order of teas in the array
57 | const reversedArray = []
58 | for(let i = teas.length-1; i >=0; i--){
59 | reversedArray.push(teas[i]);
60 | }
61 |
62 | console.log(reversedArray);
--------------------------------------------------------------------------------
/002-Arrays/006-IterationMethods/001-for-of.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | The for...of statement executes a loop that operates on a sequence of values sourced from an iterable object (such as Array, String, TypedArray, Map, Set, NodeList (and other DOM collections), as well as the arguments object, generators produced by generator functions, and user-defined iterables.).
4 |
5 | Syntax:
6 | for (variable of iterable)
7 | statement
8 |
9 | */
10 |
11 |
12 | const cars = ["Mercedes", "BMW", "Audi", "Porsche"];
13 |
14 | // Accessing the elements
15 | for (const car of cars) {
16 | console.log(car);
17 | }
--------------------------------------------------------------------------------
/002-Arrays/006-IterationMethods/002-for-in.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | The for...in statement iterates over all enumerable string properties of an object (ignoring properties keyed by symbols), including inherited enumerable properties.
4 |
5 |
6 | Syntax:
7 | for (const key in object) {
8 | if (Object.prototype.hasOwnProperty.call(object, key)) {
9 | const element = object[key];
10 | for(const car in carPrices){
11 | console.log(car);
12 | }
13 | }
14 | }
15 |
16 | */
17 |
18 | const carPrices = {
19 | "Mercedes" : 10000000,
20 | "BMW" : 20000000,
21 | "Audi" : 30000000,
22 | "Land Rover" : 40000000
23 | }
24 |
25 | for (const car in carPrices) {
26 | console.log(car); // Accessing the key
27 | console.log(carPrices[car]); // Accessing the value aasociated with current key
28 | }
29 |
30 | let cheaperCars = {}
31 | for (const car in carPrices) {
32 | if(carPrices[car] < 40000000){
33 | cheaperCars[car] = carPrices[car];
34 | }
35 | }
36 | console.log(cheaperCars);
37 |
--------------------------------------------------------------------------------
/002-Arrays/006-IterationMethods/003-forEach.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | forEach() method executes a provided function (a callback function) once for EACH array element.
4 |
5 | Syntax:
6 | array.forEach(element => {
7 |
8 | });
9 |
10 | - element is the parameter of the function
11 |
12 | OR
13 |
14 | array.forEach(function(element) {
15 |
16 | });
17 |
18 | */
19 |
20 | const cars = ["Mercedes", "BMW", "Audi", "Porsche", "Rolls Royce", "Bugatti", "Lamborghini"];
21 |
22 | // Accessing the elements
23 | cars.forEach(car => {
24 | console.log(car);
25 | });
26 |
27 |
28 | // Find luxorious car ("Rolls Royce")
29 | let luxoriousCar = "";
30 |
31 | cars.forEach(car => {
32 | if(car === "Rolls Royce"){
33 | luxoriousCar = car;
34 | }
35 | });
36 |
37 | console.log(luxoriousCar);
38 |
39 |
40 | // Find non-luxorious car (all except "Rolls Royce")
41 | let nonLuxoriousCars = [];
42 |
43 | cars.forEach(car =>{
44 | if(car === "Rolls Royce"){
45 | return;
46 | }else{
47 | nonLuxoriousCars.push(car);
48 | }
49 | });
50 |
51 | console.log(nonLuxoriousCars);
--------------------------------------------------------------------------------
/002-Arrays/006-IterationMethods/004-map.js:
--------------------------------------------------------------------------------
1 | /*
2 | map() method creates a new array, with the results of calling function, on EACH element of array
3 |
4 | */
5 |
6 | const cars = ["Mercedes", "BMW", "Audi", "Porsche", "Rolls Royce", "Bugatti", "Lamborghini"];
7 |
8 | // Find non-luxorious car (all except "Rolls Royce")
9 |
10 | const mapCars = cars.map(car =>{
11 | if(car !== "Rolls Royce"){
12 | return car;
13 | }
14 | });
15 |
16 | console.log(mapCars);
17 |
18 |
19 | /*
20 |
21 | Find average rating for each movie
22 |
23 | */
24 |
25 | let movieRatings = [
26 | { title: "Movie A", ratings: [4, 5, 3]},
27 | { title: "Movie B", ratings: [5, 5, 4]},
28 | { title: "Movie C", ratings: [3, 4, 2]}
29 | ];
30 |
31 | let averageRatings = movieRatings.map((movie) => {
32 | let sum = movie.ratings.reduce((acc, curr) => acc + curr, 0);
33 | let average = sum/movie.ratings.length;
34 |
35 | return {title: movie.title, averageRatings: average.toFixed(2)};
36 | });
37 |
38 | console.log(averageRatings);
--------------------------------------------------------------------------------
/002-Arrays/006-IterationMethods/005-flatMap.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | flatmap() method first maps all elements of an array and then creates a new array by flattening the array
4 |
5 | combination of map() and flat()
6 |
7 | */
8 |
9 | const cars = ["Mercedes", "BMW", "Audi", "Porsche", "Rolls Royce", "Bugatti", "Lamborghini"];
10 |
11 | const newCars = cars.flatMap(car => {
12 | return car.padStart(car.length+3, "new");
13 | });
14 |
15 | console.log(newCars);
--------------------------------------------------------------------------------
/002-Arrays/006-IterationMethods/006-filter.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | filter() method creates a new array with array elements that pass a test.
4 |
5 | */
6 |
7 | const cars = ["Mercedes", "BMW", "Audi", "Porsche", "Rolls Royce", "Bugatti", "Lamborghini"];
8 |
9 | const longCars = cars.filter(car => car.length >= 5);
10 | console.log(longCars);
11 |
12 |
13 | /*
14 |
15 | Find the pending tasks according to thier priority
16 |
17 | */
18 |
19 | let tasks = [
20 | { description: "Write Email", completed: false, priority: 2},
21 | { description: "Send Email", completed: true, priority: 3},
22 | { description: "Prepare presentation", completed: false, priority: 1}
23 | ];
24 |
25 | const pendingSortedTasks = tasks
26 | .filter((task) => !(task.completed))
27 | .sort((a, b) => a.priority - b.priority);
28 |
29 | console.log(pendingSortedTasks);
--------------------------------------------------------------------------------
/002-Arrays/006-IterationMethods/008-reduceRight.js:
--------------------------------------------------------------------------------
1 | /*
2 | reduceRight() method works similar to reduce(), but from RIGHT-to-LEFT
3 | */
4 |
5 | // Exa: Reversing an Array
6 |
7 | let cars = ['Mercedes', 'BMW', 'Audi'];
8 |
9 | let reversedCars = cars.reduceRight((accumulator, currentValue) => {
10 | accumulator.push(currentValue);
11 | return accumulator;
12 | }, []);
13 |
14 | console.log(reversedCars); // ['Audi', 'BMW', 'Mercedes']
15 |
16 |
17 | // Exa: Flattening array but in reverse order
18 | let nestedArray = [[1, 2], [3, 4], [5, 6]];
19 |
20 | let flattened = nestedArray.reduceRight((accumulator, currentValue) => {
21 | return accumulator.concat(currentValue);
22 | }, []);
23 |
24 | console.log(flattened); // [5, 6, 3, 4, 1, 2]
25 |
--------------------------------------------------------------------------------
/002-Arrays/006-IterationMethods/009-every.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | every() method checks if all the array values pass a test
4 |
5 | */
6 |
7 | const numbers = [45, 4, 9, 16, 25];
8 |
9 | const ifAllGreaterThan10 = numbers.every( num => num > 10);
10 | console.log(ifAllGreaterThan10);
11 |
12 | const ifAllLesserThan100 = numbers.every( num => num < 100);
13 | console.log(ifAllLesserThan100);
14 |
15 |
--------------------------------------------------------------------------------
/002-Arrays/006-IterationMethods/010-some.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | some() method checks if if some array values pass a test
4 |
5 | */
6 |
7 | const numbers = [45, 4, 9, 16, 25];
8 |
9 | const ifSomeGreaterThan10 = numbers.some( num => num > 10);
10 | console.log(ifSomeGreaterThan10);
11 |
12 | const ifSomeLesserThan0 = numbers.some( num => num < 0);
13 | console.log(ifSomeLesserThan0);
--------------------------------------------------------------------------------
/002-Arrays/006-IterationMethods/011-from.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | Array.from() method returns an Array object from any object with a length property or any iterable object
4 |
5 | */
6 |
7 | const newArray = Array.from("ABCDE");
8 | console.log(newArray);
--------------------------------------------------------------------------------
/002-Arrays/006-IterationMethods/012-keys.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | keys() method returns an Array Iterator object with the keys of an array
4 |
5 | */
6 |
7 | const cars = ["Mercedes", "BMW", "Audi", "Porsche", "Rolls Royce", "Bugatti", "Lamborghini"];
8 |
9 | const carKeys = cars.keys();
10 |
11 | for (const key of carKeys) {
12 | console.log(key);
13 | }
14 |
15 |
--------------------------------------------------------------------------------
/002-Arrays/006-IterationMethods/013-entries.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | entries() method returns an Array Iterator object with key/value pairs
4 |
5 | */
6 |
7 | const cars = ["Mercedes", "BMW", "Audi", "Porsche", "Rolls Royce", "Bugatti", "Lamborghini"];
8 |
9 | const carEntries = cars.entries();
10 |
11 | for (const car of carEntries) {
12 | console.log(car);
13 | }
--------------------------------------------------------------------------------
/002-Arrays/006-IterationMethods/014-with.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | with() method is a safe way to update elements in an array without altering the original array
4 |
5 | */
6 |
7 | const cars = ["Mercedes", "BMW", "Audi", "Porsche", "Rolls Royce", "Bugatti", "Lamborghini"];
8 |
9 | const updatedCars = cars.with(0, "Mercedes Benz");
10 |
11 | console.log(updatedCars);
--------------------------------------------------------------------------------
/002-Arrays/006-IterationMethods/015-spread.js:
--------------------------------------------------------------------------------
1 | /*
2 | - ... (spread) allows an iterable, such as an array or string, to be expanded in places where zero or more arguments (for function calls) or elements (for array) are expected.
3 |
4 | - In an object, the spread syntax enumerates the properties of an object and adds the key-value pairs to the object being created.
5 |
6 | */
7 |
8 | sum = (x, y, z, w, v) => {
9 | return x+y+z+w+v;
10 | }
11 | const numbers = [1, 2, 3, 4, 5];
12 |
13 | console.log(sum(...numbers));
--------------------------------------------------------------------------------
/003-Objects/003-rapidCodeRound.js:
--------------------------------------------------------------------------------
1 | // Problem: Create an object representing a type of tea with properties for name, type and caffeine content
2 | const tea = {
3 | teaName : "Lemon Tea",
4 | teaType : "Green Tea",
5 | caffineContent : "Low"
6 | }
7 |
8 | // Problem: Accesss and print the name and type properties of the tea object
9 | console.log(tea.teaName);
10 | console.log(tea["teaType"]);
11 |
12 | // Problem: Add a new property origin to the tea object
13 | tea.origin = "Assam";
14 | console.log(tea);
15 |
16 | // Problem: Change the caffeine level of the tea object to 'medium'
17 | tea.caffineContent = "Medium";
18 | console.log(tea);
19 |
20 | // Problem: Remove the type property from the tea object
21 | delete tea.teaType;
22 | console.log(tea);
23 |
24 | // Problem: Check if tea object has a property origin
25 | console.log("origin" in tea);
26 |
27 | // Problem: Use for...in loop to print all properties of the tea object
28 | for (const key in tea) {
29 | console.log(`${key} : ${tea[key]}`);
30 | }
31 |
32 | // Problem: Create a nested object representing different types of teas and their properties
33 | const myTeas = {
34 | greenTea : {
35 | teaName : "Green Tea",
36 | cups : {
37 | one : "1",
38 | two : "2"
39 | }
40 | },
41 | blackTea : {
42 | teaName : "Black Tea"
43 | }
44 | }
45 |
46 | // Problem : Create a copy of tea object
47 |
48 | // Shallow Copy
49 | const teaCopy = {
50 | ...myTeas
51 | } // shallow copy (only first level keys are copied)
52 | console.log(teaCopy);
53 |
54 | // Reference
55 | const anotherCopy = myTeas; // Passing reference (anotherCopy is a reference)
56 |
57 | // Deep Copy
58 | const myTeasString = JSON.stringify(myTeas);
59 | const myTeasCopy = JSON.parse(myTeasString);
60 |
61 | console.log(myTeasCopy);
62 |
63 | // Problem : Add a custom method describe to the tea object that returns a description string
64 | // Problem : Merge two objects representing different teas into one
65 |
--------------------------------------------------------------------------------
/003-Objects/004-generalObjectMethods.js:
--------------------------------------------------------------------------------
1 | /*
2 | - Object.hasOwn(object, property)
3 | - Object.assign(target, source)
4 | - Object.create(object)
5 | - Object.entries(object)
6 | - Object.fromEntries()
7 | - Object.keys(object)
8 | - Object.values(object)
9 | - Object.groupBy(object, callback)
10 | */
11 |
12 | const car1 = {
13 | model : "Land Rover",
14 | brand : "Range Rover",
15 | color : "Black"
16 | }
17 |
18 | const car2 = {
19 | model : "Defender",
20 | color : "Red",
21 | parentBrand : "TATA"
22 | }
23 |
24 | console.log(car1);
25 | console.log(car2);
26 |
27 | // Object.hasOwn(object, property) - returns true if the specified object has the indicated property as its own property. If the property is inherited, or does not exist, the method returns false.
28 |
29 | console.log(Object.hasOwn(car1, "brand"));
30 |
31 | // Object.assign(target, source) - Copies enumerable own properties from a source object to a target object, returns modified target object
32 | Object.assign(car1, car2);
33 |
34 | console.log(car1);
35 | console.log(car2);
36 |
37 |
38 | // Object.create(object) - Creates an object from an existing object as the prototype of the newly created object
39 | const car3 = Object.create(car2);
40 |
41 | console.log(car3); // {}
42 |
43 | car3.model = "Discovery";
44 | car3.brand = "Land Rover";
45 | car3.price = "INR 70,00,000/-"
46 |
47 | console.log(car3);
48 |
49 |
50 | // Object.entries(object) - Returns an ARRAY of the given object's own ennumerable [key, value] pairs
51 | const objectEntries = Object.entries(car3);
52 | console.log(objectEntries);
53 |
54 | // can be used with loops
55 | for(let [key, value] of Object.entries(car2)){
56 | console.log([key, value]);
57 | }
58 |
59 | // makes it simple to convert OBJECTS to MAP
60 | const myMap = new Map(Object.entries(car2));
61 | console.log(myMap);
62 |
63 |
64 | // Object.fromEntries() - Creates an object from a list of keys/values
65 | const fruits = [
66 | ["apples", 300],
67 | ["pears", 900],
68 | ["bananas", 500]
69 | ];
70 |
71 | const fruitObject = Object.fromEntries(fruits);
72 | console.log(fruitObject);
73 |
74 |
75 | // Object.keys(object) - Returns an array of the enumerable keys of an object
76 | const keyArray = Object.keys(fruitObject);
77 | console.log(keyArray);
78 |
79 | // Object.values(object) - Returns an array of the enumerable property values of an object
80 | const valueArray = Object.values(fruitObject);
81 | console.log(valueArray);
82 |
83 |
84 | // Object.groupBy(object, callback) - groups elements of an object according to string values returned from a callback function. Works only with enumerable properties.
85 |
86 | const myFruits = [
87 | {name:"apples", quantity:300},
88 | {name:"bananas", quantity:500},
89 | {name:"oranges", quantity:200},
90 | {name:"kiwi", quantity:150}
91 | ];
92 |
93 | function myCallback({ quantity }) {
94 | return quantity > 200 ? "ok" : "low";
95 | }
96 |
97 | const result = Object.groupBy(myFruits, myCallback);
98 | console.log(result);
99 |
100 |
--------------------------------------------------------------------------------
/003-Objects/005-propertyManagementMethods.js:
--------------------------------------------------------------------------------
1 | /*
2 | - Object.defineProperty(object, property, descriptor)
3 | - Object.defineProperties(object, descriptors)
4 | - Object.getOwnPropertyDescriptor(object, property)
5 | - Object.getOwnPropertyDescriptors(object)
6 | - Object.getOwnPropertyNames(object)
7 | - Object.getPrototypeOf(object)
8 | */
9 |
10 | // Object.defineProperty(object, property, descriptor)
11 | // Adding a new property to an object
12 | // Changing property values
13 | // Changing property metadata
14 | // Changing object getters and setters
15 |
16 | const person1 = {
17 | firstName: "Tony",
18 | lastName : "Stark"
19 | };
20 |
21 | const person2 = {
22 | firstName : "Steve",
23 | lastName : "Rogers",
24 | age : "45"
25 | }
26 |
27 | Object.defineProperty(person1, "age", {value:"50"});
28 | console.log(person1); // age property exits but will not be shown in output, because properties added using Object.defineProperty() are non-enumerable (enumerable : false). They are also non-writable(writable : false), non-configurable (configurable : false).
29 | console.log(person1.age);
30 |
31 | Object.defineProperty(person1, "superhero", {value : "Iron Man", enumerable : true});
32 | console.log(person1);
33 |
34 |
35 | // Object.defineProperties(object, descriptors) - Adding or changing multiple object properties
36 | Object.defineProperties(person1, {
37 | powerSource : {
38 | value : "Arc Reactor",
39 | enumerable : true
40 | },
41 | suits : {
42 | value : ["Mark 1", "Mark 10", "Mark 42"],
43 | enumerable : true
44 | },
45 | industries : {
46 | value : {
47 | name : "Stark Industires",
48 | doamin : "Engineering",
49 | CEO : "Pepper Pots",
50 | owner : "Tony Strak"
51 | },
52 | enumerable: true
53 | }
54 | });
55 |
56 | console.log(person1);
57 |
58 |
59 | // Object.getOwnPropertyDescriptor(object, property) - returns an object describing the configuration of a specific property on a given object
60 | const descriptor1 = Object.getOwnPropertyDescriptor(person1, "superhero");
61 | console.log(descriptor1);
62 |
63 | // Object.getOwnPropertyDescriptors(object) - returns an object describing the configuration of all properties on a given object
64 | const descriptor2 = Object.getOwnPropertyDescriptors(person1);
65 | console.log(descriptor2);
66 |
67 |
68 | // Object.getOwnPropertyNames(object) - returns an array of all properties (including non-enumerable properties except for those which use Symbol) found directly in a given object.
69 |
70 | const propertyNames = Object.getOwnPropertyNames(person1);
71 | console.log(propertyNames);
72 |
73 |
74 | // Object.getPrototypeOf(object) - returns the prototype
75 | const prototype1 = Object.getPrototypeOf(person1);
76 | console.log(prototype1);
77 |
78 | console.log(Object.getPrototypeOf(person1) === Object.getPrototypeOf(person2));
79 |
80 |
--------------------------------------------------------------------------------
/003-Objects/006-objectProtectionMethods.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | - const
4 | - Object.preventExtensions(object)
5 | - Object.isExtensible(object)
6 | - Object.seal(object)
7 | - Object.isSealed(object)
8 | - Object.freeze(object)
9 | - Object.isFrozen(object)
10 |
11 | */
12 |
13 | // const - prevents re-assignment (can still change the value of a property, delete a property or create a new property)
14 | const person = {
15 | firstName: 'Tony',
16 | lastName: 'Stark',
17 | superhero: 'Iron Man',
18 | powerSource: 'Arc Reactor',
19 | suits: [ 'Mark 1', 'Mark 10', 'Mark 42' ],
20 | industries: {
21 | name: 'Stark Industires',
22 | doamin: 'Engineering',
23 | CEO: 'Pepper Pots',
24 | owner: 'Tony Strak'
25 | }
26 | }
27 |
28 |
29 | // Object.preventExtensions(object) - prevents new properties from ever being added to an object. It also prevents the object's prototype from being re-assigned.
30 | Object.preventExtensions(person);
31 |
32 | // Object.defineProperty(person, "car", {value : "R8"}); -> TypeError
33 |
34 |
35 | // Object.isExtensible(object) - Returns true if properties can be added to an object
36 | console.log(Object.isExtensible(person));
37 |
38 |
39 | // Object.seal(object) - Sealing an object prevents extensions and makes existing properties non-configurable. A sealed object has a fixed set of properties: new properties cannot be added, existing properties cannot be removed, their enumerability and configurability cannot be changed, and its prototype cannot be re-assigned. Values of existing properties can still be changed as long as they are writable. seal() returns the same object that was passed in.
40 |
41 |
42 | // Object.isSealed(object) - returns true if object is sealed
43 |
44 |
45 | // Object.freeze(object) - prevents extensions and makes existing properties non-writable and non-configurable. A frozen object can no longer be changed: new properties cannot be added, existing properties cannot be removed, their enumerability, configurability, writability, or value cannot be changed, and the object's prototype cannot be re-assigned. freeze() returns the same object that was passed in.
46 |
47 |
48 | // Object.isFrozen() - returns true if an object is frozen.
49 |
50 |
51 |
--------------------------------------------------------------------------------
/004-Polyfills/PolyfillsForMethods-MachineCoding/001-forEach.js:
--------------------------------------------------------------------------------
1 | // Exa: Error: .forEach function does not exist on arr variable
2 |
3 | // How to approach - Understand real signature of funtion
4 |
5 | const arr = [10,20,30];
6 |
7 | const res = arr.forEach(function(value, index){
8 | console.log(`Value at ${index} is ${value}`);
9 | });
10 |
11 | const userFunction = function(value, index){
12 | console.log(`Value: ${value}, Index: ${index}`);
13 | }
14 | const result = arr.forEach(userFunction);
15 |
16 | // console.log(`Returned: ${res}`);
17 |
18 | // Signature:
19 | // parameter for forEach -> function; function parameters -> index, value
20 | // what forEach does? -> calls function for every value
21 | // return -> no return
22 |
23 | // Writing Polyfill for forEach()
24 |
25 | if(!Array.prototype.myForEach){
26 |
27 | Array.prototype.myForEach = function(userFunction){
28 |
29 | const originalArr = this; // Points to current object
30 |
31 | for(let i = 0; i < originalArr.length; i++){
32 | userFunction(originalArr[i], i);
33 | }
34 | }
35 | }
36 |
37 | const myResult = arr.myForEach(userFunction);
--------------------------------------------------------------------------------
/004-Polyfills/PolyfillsForMethods-MachineCoding/002-map.js:
--------------------------------------------------------------------------------
1 | // Signature:
2 | // parameter -> callback
3 | // return -> new array (with result of work asked to be done by user)
4 | // does not modify original array
5 | // performs specified operation on each element, and push the result of that operation into new array
6 |
7 | const multiplyBy10 = function(value){
8 | return value*10;
9 | }
10 |
11 | const arr = [1, 2, 3];
12 |
13 | const result = arr.map(multiplyBy10);
14 |
15 | console.log(result);
16 |
17 | // Writing pollyfill for map()
18 |
19 | if(!Array.prototype.myMap){
20 |
21 | Array.prototype.myMap = function(userFunction){
22 |
23 | const mapResult = [];
24 |
25 | for(let i = 0; i < this.length; i++){
26 | mapResult.push(userFunction(this[i]));
27 | }
28 |
29 | return mapResult;
30 | }
31 | }
32 |
33 | const myResult = arr.myMap(multiplyBy10);
34 | console.log(myResult);
--------------------------------------------------------------------------------
/004-Polyfills/PolyfillsForMethods-MachineCoding/003-filter.js:
--------------------------------------------------------------------------------
1 | // Signature:
2 | // Parameter -> callback
3 | // Return -> returns a new array, with only those elements that pass the test
4 | // Functionality -> calls function for every value, and adds current value to the result array if it passes the test (returns true)
5 |
6 |
7 |
8 |
9 | const divisibleBy3 = function(value){
10 | if(value%3 === 0){
11 | return true;
12 | }else{
13 | return false;
14 | }
15 | }
16 |
17 | const arr = [10, 20, 30, 40, 50, 60];
18 |
19 | const result = arr.filter(divisibleBy3);
20 | console.log(result);
21 |
22 | if(!Array.prototype.myFilter){
23 |
24 | Array.prototype.myFilter = function(userFunction){
25 |
26 | const filterResult = [];
27 |
28 | for(let i = 0; i < this.length; i++){
29 | if(userFunction(this[i])){
30 | filterResult.push(this[i]);
31 | }
32 | }
33 |
34 | return filterResult;
35 | }
36 | }
37 |
38 | const myResult = arr.myFilter(divisibleBy3);
39 | console.log(myResult);
--------------------------------------------------------------------------------
/004-Polyfills/PolyfillsForMethods-MachineCoding/004-reduce.js:
--------------------------------------------------------------------------------
1 | const arr = [1, 2, 3, 4, 5];
2 |
3 | console.log(arr.reduce((accumulator, currentValue) => accumulator + currentValue, 0));
4 | console.log(arr.reduce((accumulator, currentValue) => accumulator + currentValue, 15));
5 | console.log(arr.reduce((accumulator, currentValue) => accumulator + currentValue));
6 |
7 |
8 | if (!Array.prototype.myReduce){
9 |
10 | Array.prototype.myReduce = function(cb, initialValue = undefined){
11 |
12 | let acc = initialValue || this[0];
13 |
14 | let startIndex = initialValue ? 0 : 1;
15 |
16 | for(let i = startIndex; i < this.length; i++){
17 | acc = cb(acc, this[i]);
18 | }
19 |
20 | return acc;
21 | }
22 | }
23 |
24 | console.log(arr.myReduce((acc, curr) => acc + curr, 0));
25 | console.log(arr.myReduce((acc, curr) => acc + curr, 15));
26 | console.log(arr.myReduce((acc, curr) => acc + curr));
--------------------------------------------------------------------------------
/004-Polyfills/pollyfillsBasics.js:
--------------------------------------------------------------------------------
1 | // Prototype Basics
2 |
3 | console.log(Array.prototype);
4 |
5 | const arr = [1,2,3]
6 |
7 | console.log(arr.__proto__);
8 |
9 | Array.prototype.ironMan = function(){
10 | return "I am Iron Man";
11 | }
12 |
13 | const res = arr.ironMan();
14 | console.log(res);
15 |
16 |
17 | // Polyfill basics
18 |
19 | if(!Array.prototype.newFunction){
20 |
21 | // We have an option to throw error ("Please update your browser")
22 |
23 | // OR
24 |
25 | // We can explicitly define it
26 | Array.prototype.fill = function(){
27 |
28 | };
29 |
30 | // Fallback - Polyfill
31 | }
32 |
33 | arr.fill();
34 |
35 |
--------------------------------------------------------------------------------
/005-ObjectsAndClasses/001-basics.js:
--------------------------------------------------------------------------------
1 | const obj1 = {
2 | fname : 'Tony',
3 | lname : 'Stark',
4 | getFullName : function(){
5 | return `${this.fname} ${this.lname}`;
6 | }
7 | };
8 |
9 | const obj2 = {
10 | fname : 'Steve',
11 | lname : 'Rogers',
12 | getFullName : function(){
13 | return `${this.fname} ${this.lname}`;
14 | }
15 | };
16 |
17 | // DRY - Do Not Repeat Yourself, is violated here
18 | console.log(obj1.getFullName());
19 | console.log(obj1.getFullName());
20 |
21 | const obj3 = {
22 | fname : 'Bruce',
23 | lname : 'Banner',
24 | };
25 |
26 | // console.log(obj3.getFullName());
27 | // This will throw error.
28 | // The code will first check in obj3 if getFullName exist
29 | // If the method is not found, it will check in __proto__ (points to predefined prototypes of Objects)
30 | // Other functions will work
31 |
32 | console.log(obj3.toString());
33 |
34 | obj3.__proto__ = obj2; // now __proto__ in obj3 points to obj1
35 |
36 | console.log(obj3.getFullName()); // now this works
37 |
38 | console.log(obj3.toString()); // This will also work
39 | // __proto__ of obj3 is pointing to obj1, which has __proto__ that points to prototypes of objects
40 | // It will continue to look until it finds null
41 |
42 | console.log(obj1.__proto__.__proto__); // returns null
43 |
44 | obj3.__proto__ = null;
45 | // console.log(obj3.toString());
46 | // This will throw error because now we broke the chain
47 |
48 | // Prototype Inheritance/ Prototype Chaining
49 |
50 |
51 | // Why everything in JS is object
52 |
53 | const arr = [1, 2, 3];
54 | console.log(arr.__proto__); // Object (Array)
55 | console.log(arr.__proto__.__proto__); // Object
56 |
57 | const string = "ThisIsAString";
58 | console.log(string.__proto__); // String
59 | console.log(string.__proto__.__proto__); // Object
60 |
--------------------------------------------------------------------------------
/005-ObjectsAndClasses/002-class.js:
--------------------------------------------------------------------------------
1 | class Person {
2 |
3 | // Parameterized Constructor
4 | constructor(fname, lname){
5 | this.fname = fname;
6 | this.lname = lname;
7 | }
8 |
9 | // If we don't write a constructor, Deafult Constructor is initialized
10 | // constructor(){
11 | // }
12 |
13 | getFullName(){
14 | return `${this.fname} ${this.lname}`;
15 | }
16 | }
17 |
18 | const p1 = new Person("Tony", "Stark");
19 | const p2 = new Person("Bruce", "Banner");
20 |
21 | console.log(p1.getFullName());
22 | console.log(p2.getFullName());
23 |
24 | console.log(Person.prototype); // Object
25 | console.log(p1.__proto__); // Object
26 |
27 | // Here we let JavaScript handled the prototype by itself
28 | // Whenever we create a new object (say obj1), it gets the prototype from Person class
29 | // __p1.proto__ = Person.prototype
30 |
31 | // Since, __proto__ of obj1 and obj2 are same. We say that obj1 and obj2 belong to same class
32 |
33 |
34 | // Code looks clean now - Syntax Sugar
--------------------------------------------------------------------------------
/006-DOM/001-Basics/External JS/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Document
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/006-DOM/001-Basics/External JS/index.js:
--------------------------------------------------------------------------------
1 | console.log(window);
2 | // NodeJS -> Reference Error: window is not defined
3 | // We can use window only in browser
4 |
5 | window.document.write("Hello From JS");
6 | // This will write Hello from JS on web page (we have manipulated the HTML of website)
--------------------------------------------------------------------------------
/006-DOM/001-Basics/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Document
7 |
8 |
9 |
10 |
11 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/006-DOM/002-Example/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Document
7 |
8 |
9 |
10 |
14 |
15 |
16 | Black Background
17 | White Background
18 | Green Button
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/006-DOM/002-Example/index.js:
--------------------------------------------------------------------------------
1 | function changeBackgroundColorBlack(){
2 | document.body.style.backgroundColor = 'black';
3 | }
4 |
5 | function changeBackgroundColorWhite(){
6 | document.body.style.background = 'white';
7 | }
8 |
9 | // DRY is violated
10 |
11 |
12 | // Fixing DRY
13 |
14 | function changeBackgroundColor(color){
15 | document.body.style.backgroundColor = color;
16 | }
--------------------------------------------------------------------------------
/006-DOM/003-EventListeners/001-ButtonExample/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Document
7 |
8 |
9 |
10 |
14 |
15 |
16 | Dark Button
17 |
18 |
19 | Toggle
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/006-DOM/003-EventListeners/001-ButtonExample/index.js:
--------------------------------------------------------------------------------
1 | function changeBackgroundColor(color){
2 | document.body.style.backgroundColor = color;
3 | }
4 |
5 | // referencing dark-button
6 | const darkButton = document.getElementById("dark-button");
7 |
8 | // Check in browser console, of we targeted the correct button
9 | console.log(darkButton);
10 |
11 | // Adding event listener to button
12 | // params -> event, listener function
13 | // whenever the event occurs, listener function is executed
14 | darkButton.addEventListener('click', function(){
15 | console.log('I got clicked');
16 | changeBackgroundColor('black');
17 | });
18 |
19 | // can we perform another function on same button? -> YES
20 |
21 | darkButton.addEventListener('click', function(){
22 | console.log('Another function');
23 | });
24 |
25 |
26 | // referencing theme-button
27 | const themeButton = document.getElementById("theme-button");
28 | console.log(themeButton);
29 |
30 | themeButton.addEventListener('click', function(){
31 | console.log(document.body.style.backgroundColor);
32 |
33 | const currentColor = document.body.style.backgroundColor;
34 |
35 | if(!currentColor || currentColor == "white"){
36 | changeBackgroundColor("black");
37 | themeButton.innerText = "Light Mode"; // Overwriting the button label
38 | }else{
39 | changeBackgroundColor("white");
40 | themeButton.innerText = "Dark Mode"; // Overwriting the button label
41 | }
42 | });
--------------------------------------------------------------------------------
/006-DOM/003-EventListeners/002-BasicTodoExample/README.md:
--------------------------------------------------------------------------------
1 | ### Todo App
2 |
3 | ## Wireframe
4 | 
5 |
6 | ## Functionality
7 |
8 | - **Add Task:** Users can add a task by typing in the textbox and clicking the 'Add' button.
9 | - **Delete Task:** Users can delete individual tasks by clicking the 'Delete' button next to the task.
10 | - **Clear All Tasks:** Users can clear the entire list of tasks by clicking the 'Delete All' button.
--------------------------------------------------------------------------------
/006-DOM/003-EventListeners/002-BasicTodoExample/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Todo App
7 |
8 |
9 | Todo App
10 |
11 |
12 |
13 |
14 |
15 | Add
16 | Delete All
17 |
18 |
19 |
20 |
24 |
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/006-DOM/003-EventListeners/002-BasicTodoExample/index.js:
--------------------------------------------------------------------------------
1 | console.log('Todo App');
2 |
3 | // Referencing todo-input
4 | const todoInput = document.getElementById('todo-input');
5 |
6 | // Referencing add-button
7 | const addButton = document.getElementById('add-button');
8 |
9 | // Referencing to-do-items-container
10 | const todoItemsContainer = document.getElementById('to-do-items-container');
11 |
12 | // Referencing delete-all-button
13 | const deleteAllButton = document.getElementById('delete-all-button')
14 |
15 | // Adding event listener to addButton
16 | addButton.addEventListener('click', function(){
17 | // console.log(addButton);
18 |
19 | // Getting user input
20 | const inputValue = todoInput.value;
21 | console.log(inputValue);
22 |
23 | // Make tag for each input
24 | const li = document.createElement('li'); //
25 | console.log(li);
26 |
27 | // Adding value to tag
28 | li.innerText = inputValue; // (value)
29 | console.log(li);
30 |
31 | // Creating delete button
32 | const deleteButton = document.createElement('button');
33 | deleteButton.innerText = 'Clear';
34 |
35 | // Adding event listener to deleteButton
36 | deleteButton.addEventListener('click', function(){
37 | li.remove();
38 | });
39 |
40 | // Adding delete button (adding delete button to each li)
41 | li.appendChild(deleteButton);
42 |
43 |
44 | // Displaying tasks on screen (adding to )
45 | todoItemsContainer.appendChild(li);
46 |
47 | // Make user input blank
48 | todoInput.value = '';
49 |
50 | });
51 |
52 |
53 | // Adding event listener to deleteAllButton
54 | deleteAllButton.addEventListener('click', function(){
55 |
56 | // Method 1
57 | //todoItemsContainer.innerHTML = "";
58 |
59 | // Method 2
60 | let todoItemsContainerChild = todoItemsContainer.lastElementChild;
61 |
62 | while(todoItemsContainerChild){
63 | todoItemsContainer.removeChild(todoItemsContainerChild);
64 | todoItemsContainerChild = todoItemsContainer.lastElementChild;
65 | }
66 |
67 | todoInput.value = '';
68 | });
--------------------------------------------------------------------------------
/006-DOM/003-EventListeners/002-BasicTodoExample/wireframe.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vsh26/JavaScrpit/3186e585fe2b45e551defbdaacdb8531c23894d8/006-DOM/003-EventListeners/002-BasicTodoExample/wireframe.png
--------------------------------------------------------------------------------
/007-SpeedJS/001-dataTypes.js:
--------------------------------------------------------------------------------
1 | let number = 42; // Number
2 | let text = "hello"; // String
3 | let isTrue = true; // Boolean
4 | let nothing = null; // Object (it is null, but typeof returns object)
5 | let undefinedVar = undefined // undefined
6 | let symbol = Symbol() // Symbol
7 |
8 | // Conversion (String -> Number)
9 |
10 | let num1 = "42";
11 | let num2 = "42a"
12 |
13 | let num1Conversion01 = Number(num1);
14 | let num2Conversion01 = Number(num2);
15 | let num1Conversion02 = +num1;
16 | let num2Conversion02 = +num2;
17 | let num1Conversion03 = parseInt(num1);
18 | let num2Conversion03 = parseInt(num2);
19 |
20 | console.log(num1Conversion01); // 42
21 | console.log(typeof num1Conversion01); // number
22 | console.log(num2Conversion01); // NaN
23 | console.log(typeof num2Conversion01); // number
24 | console.log(num1Conversion02); // 42
25 | console.log(typeof num1Conversion02); // number
26 | console.log(num2Conversion02); // Nan
27 | console.log(typeof num2Conversion02); // number
28 | console.log(num1Conversion03); // 42
29 | console.log(typeof num1Conversion03); // number
30 | console.log(num2Conversion03); // 42
31 | console.log(typeof num2Conversion03); // number
32 |
33 |
34 | // Conversion (Number -> String)
35 |
36 | let num = 123;
37 | let convertedStr = String(num);
38 |
39 | console.log(convertedStr); // 123
40 | console.log(typeof convertedStr); // string
41 |
42 |
43 | // Arithmetic Operators
44 |
45 | let a = 10;
46 | let b = 3;
47 |
48 | let sum = a + b;
49 | let difference = a - b;
50 | let product = a * b;
51 | let quotient = a / b;
52 | let remainder = a % b;
53 | let power = a ** b;
54 |
55 | // Comparision
56 |
57 | let x = 10;
58 | let y = "10";
59 |
60 | console.log(x == y); // true (checks for value)
61 | console.log(x != y); // false
62 | console.log(x === y); // false (checks for value as well as data-type)
63 | console.log(x !== y); // true
64 | console.log(x < y); // false
65 | console.log(x <= y); // true
66 | console.log(x > y); // false
67 | console.log(x >= y); // true
68 |
69 |
70 | // Math library
71 |
72 | // Mostly used Math functions
73 | // Math.max(a, b)
74 | // Math.min(a, b)
75 | // Math.random()
76 | // Math.floor(num)
77 |
78 | console.log(Math.max(10, 5)); // 10
79 | console.log(Math.min(10, 5)); // 5
80 | console.log(Math.random()); // retruns random number between 0(inclusive) and 1(exclusive)
81 | console.log((10*Math.random())); // retruns random number between 0(inclusive) and 10(exclusive)
82 |
83 | // Exa: create a function that returns a random number between 1 and 6
84 | function diceFunction(){
85 | const result = Math.floor((6*Math.random())) + 1;
86 | return result;
87 | }
88 |
89 | console.log(diceFunction());
90 |
91 | // Mostly used string functions
92 | // .length
93 | // .toUpperCase()
94 | // .toLowerCase()
95 | // .indexOf(str)
96 | // .slice(start(I), end(NI))
97 |
--------------------------------------------------------------------------------
/007-SpeedJS/002-arrayAndObjects.js:
--------------------------------------------------------------------------------
1 | // Arrays
2 |
3 | let chaiTypes = ["Masala Chai", "Ginger Chai", "Green Tea", "Lemon Tea"];
4 |
5 | console.log(`Total chai types: ${chaiTypes.length}`);
6 | console.log(chaiTypes[1]);
7 |
8 | // Important array methods
9 | // .push(value) -> add the element to the end of the array
10 | // .pop() -> removes the element from the last index of the array, returns the poopped element
11 | // .splice() -> add elements to array
12 | // .forEach()
13 | // .concat()
14 |
15 | let newChaiTypes = [...chaiTypes, "Chamolina Tea", "Oolong Tea"];
16 | console.log(newChaiTypes);
17 |
18 |
19 | // Objects
20 | let chaiReceipe = {
21 | name: "Masala Chai",
22 | ingredients: {
23 | teaLeaves: "Assan Tea",
24 | milk: "Full cream milk",
25 | sugar: "Brown sugar",
26 | spices: ["Daalchini", "Ginger"]
27 | },
28 | instruction: "Boil water, add tea leaves, milk, sugar and spices"
29 | };
30 |
31 | console.log(chaiReceipe);
32 | console.log(chaiReceipe.ingredients.spices[1]);
33 |
34 | let updatedChaiReceipe = {
35 | ...chaiReceipe,
36 | instruction: "Boil water, add tea leaves, milk, sugar, spices with love" // overriding
37 | };
38 |
39 | console.log(updatedChaiReceipe);
40 |
41 | // Destructuring assignment
42 | let {name, ingredients} = chaiReceipe;
43 | let [firstChai, secondChai] = chaiTypes;
44 |
45 | let {myName, myIngredients} = chaiReceipe;
46 |
47 | console.log(ingredients);
48 | console.log(myIngredients); // undefined
49 |
50 |
51 | // let [value, setValue] = useState()
--------------------------------------------------------------------------------
/007-SpeedJS/003-controlFlow.js:
--------------------------------------------------------------------------------
1 | /*
2 | If amount >= 1000, give 10% discount
3 | */
4 |
5 | function calculateTotalBill(amount){
6 | if(amount >= 1000){
7 | return amount * 0.9;
8 | }
9 |
10 | return amount;
11 |
12 | // ternary operators
13 | // return amount >= 1000 ? amount * 9 : amount;
14 | }
15 |
16 | const total = calculateTotalBill(1200);
17 | console.log(total);
18 |
19 | console.log(calculateTotalBill(900));
20 |
21 |
22 | /*
23 | Traffic Light System
24 | */
25 |
26 | function trafficLight(color){
27 |
28 | const colorStr = color.toLowerCase();
29 |
30 | switch(colorStr){
31 | case "red":
32 | console.log("Stop");
33 | break;
34 |
35 | case "green":
36 | console.log("Go");
37 | break;
38 |
39 | case "yellow":
40 | console.log("Go slow");
41 | break;
42 |
43 | case "deafult":
44 | console.log("Follow what traffic police says");
45 | }
46 | }
47 |
48 | trafficLight("Yellow");
49 |
50 | /*
51 | Truthy Falsy
52 | */
53 |
54 | function checkTruthyValue(value){
55 | if(value){
56 | console.log("Truthy");
57 | }else{
58 | console.log("Falsy");
59 | }
60 | }
61 |
62 | checkTruthyValue(1); // Truthy
63 | checkTruthyValue(0); // Falsy
64 | checkTruthyValue(-1); // Truthy
65 | checkTruthyValue(10); // Truthy
66 | checkTruthyValue(-10); // Truthy
67 | checkTruthyValue(1.2); // Truthy
68 | checkTruthyValue(-1.2); // Truthy
69 | checkTruthyValue("abc"); // Truthy
70 | checkTruthyValue(""); // Falsy
71 | checkTruthyValue(true); // Truthy
72 | checkTruthyValue(false); // Falsy
73 | checkTruthyValue(null); // Falsy
74 | checkTruthyValue(undefined); // Falsy
75 | checkTruthyValue([]); // Truthy
76 | checkTruthyValue([0]); // Truthy
77 | checkTruthyValue([1, 2, 3]); // Truthy
78 | checkTruthyValue({}); // Truthy
79 | checkTruthyValue({a: 1, b:2}); // Truthy
80 |
--------------------------------------------------------------------------------
/007-SpeedJS/004-iteration.js:
--------------------------------------------------------------------------------
1 | /*
2 | calculate total sales
3 | */
4 |
5 | let SalesData = [
6 | { product: "Laptop", price: 1200 },
7 | { product: "Smartphone", price: 800 },
8 | { product: "Headphones", price: 150 },
9 | { product: "Keyboard", price: 80 }
10 | ];
11 |
12 | // Method 1: Using loops
13 |
14 | let total = 0;
15 | for(sale of SalesData){
16 | total += sale.price;
17 | }
18 | console.log(total);
19 |
20 | // Method 2: using reduce
21 |
22 | const totalSales = SalesData.reduce((acc, sale) => acc + sale.price, 0);
23 | console.log(totalSales);
24 |
25 |
26 |
27 | /*
28 |
29 | inventory < 50 (low stock items). Get low stock items
30 |
31 | */
32 |
33 | let inventory = [
34 | { name: "Widget A", stock: 30 },
35 | { name: "Widget B", stock: 120 },
36 | { name: "Widget C", stock: 45 },
37 | { name: "Widget D", stock: 70 }
38 | ];
39 |
40 | // using filter()
41 |
42 | const lowStockItems = inventory.filter((item) => item.stock < 50 );
43 | console.log(lowStockItems);
44 |
45 |
46 |
47 | /*
48 |
49 | Find most active user
50 |
51 | */
52 |
53 | let userActivity = [
54 | { user: "Alice", activityCount: 45 },
55 | { user: "Bob", activityCount: 72 },
56 | { user: "Charlie", activityCount: 33 }
57 | ];
58 |
59 | // only use reduce
60 |
61 | let mostActiveUser = userActivity.reduce((maxUser, user) =>
62 | user.activityCount > maxUser.activityCount ? user : maxUser
63 | );
64 |
65 | console.log(mostActiveUser);
66 |
67 |
68 | /*
69 | category-wise bill (Total of food, total of utilities)
70 | */
71 |
72 | let expenses = [
73 | { description : "Groceries" , amount : 50, category : "Food"},
74 | { description : "Electricity Bill", amount : 100, category : "Utilities"},
75 | { description : "Dinner", amount : 30, category : "Food"},
76 | { description : "Internet Bill", amount : 50, category : "Utilities"}
77 | ];
78 |
79 | // This code is static
80 | const expenseReport = expenses.reduce(
81 | (report, expense) => {
82 | report[expense.category] += expense.amount;
83 | return report;
84 | },
85 | {Food : 0, Utilities: 0}
86 | );
87 |
88 | console.log(expenseReport);
89 |
90 |
91 | // Dynamic (if we don't know the categories)
92 | const dynamicExpenseReport = expenses.reduce(
93 | (report, expense) => {
94 | report[expense.category] = (report[expense.category] || 0) + expense.amount;
95 | return report;
96 | },
97 | {}
98 | );
99 |
100 | console.log(dynamicExpenseReport);
101 |
102 | /*
103 |
104 | Find the pending tasks according to thier priority
105 |
106 | */
107 |
108 | let tasks = [
109 | { description: "Write Email", completed: false, priority: 2},
110 | { description: "Send Email", completed: true, priority: 3},
111 | { description: "Prepare presentation", completed: false, priority: 1}
112 | ];
113 |
114 | const pendingSortedTasks = tasks
115 | .filter((task) => !(task.completed))
116 | .sort((a, b) => a.priority - b.priority);
117 |
118 | console.log(pendingSortedTasks);
119 |
120 |
121 | /*
122 |
123 | Find average rating for each movie
124 |
125 | */
126 |
127 | let movieRatings = [
128 | { title: "Movie A", ratings: [4, 5, 3]},
129 | { title: "Movie B", ratings: [5, 5, 4]},
130 | { title: "Movie C", ratings: [3, 4, 2]}
131 | ];
132 |
133 | let averageRatings = movieRatings.map((movie) => {
134 | let sum = movie.ratings.reduce((acc, curr) => acc + curr, 0);
135 | let average = sum/movie.ratings.length;
136 |
137 | return {title: movie.title, averageRatings: average.toFixed(2)};
138 | });
139 |
140 | console.log(averageRatings);
--------------------------------------------------------------------------------
/007-SpeedJS/005-functions.js:
--------------------------------------------------------------------------------
1 | function greet(name) {
2 | console.log(`Hello ${name}`);
3 | }
4 |
5 | greet("Iron Man");
6 |
7 | // Scope of this variable is global
8 | let globalVar = "I am global";
9 |
10 | function modifyGlobal(){
11 | globalVar = "I am modified";
12 |
13 | let blockScopedVar = "I am block-scoped";
14 | }
15 |
16 |
17 | // IIFE - Immidiately Invoked Function Expression
18 | let config = (function () {
19 | let settings = {
20 | theme: "dark",
21 | };
22 | return settings;
23 | })();
24 |
25 |
26 | // call()
27 |
28 | let person1 = {
29 | personName: "Tony",
30 | greet: function(){
31 | console.log(`Hello, ${this.personName}`);
32 | }
33 | };
34 |
35 | let person2 = {
36 | personName: "Steve"
37 | };
38 |
39 | person1.greet();
40 | person1.greet.call(person2);
41 |
42 | const bindGreet = person1.greet.bind(person2); // returns a function
43 | console.log(bindGreet); // person1.greet.call(person2);
44 | console.log(bindGreet()); // Hello Steve
45 | //undefined
46 | bindGreet();
47 |
48 |
--------------------------------------------------------------------------------
/008-MachineCoding/ArrayMethods/iteration.js:
--------------------------------------------------------------------------------
1 | /*
2 | calculate total sales
3 | */
4 |
5 | let SalesData = [
6 | { product: "Laptop", price: 1200 },
7 | { product: "Smartphone", price: 800 },
8 | { product: "Headphones", price: 150 },
9 | { product: "Keyboard", price: 80 }
10 | ];
11 |
12 | // Method 1: Using loops
13 |
14 | let total = 0;
15 | for(sale of SalesData){
16 | total += sale.price;
17 | }
18 | console.log(total);
19 |
20 | // Method 2: using reduce
21 |
22 | const totalSales = SalesData.reduce((acc, sale) => acc + sale.price, 0);
23 | console.log(totalSales);
24 |
25 |
26 |
27 | /*
28 |
29 | inventory < 50 (low stock items). Get low stock items
30 |
31 | */
32 |
33 | let inventory = [
34 | { name: "Widget A", stock: 30 },
35 | { name: "Widget B", stock: 120 },
36 | { name: "Widget C", stock: 45 },
37 | { name: "Widget D", stock: 70 }
38 | ];
39 |
40 | // using filter()
41 |
42 | const lowStockItems = inventory.filter((item) => item.stock < 50 );
43 | console.log(lowStockItems);
44 |
45 |
46 |
47 | /*
48 |
49 | Find most active user
50 |
51 | */
52 |
53 | let userActivity = [
54 | { user: "Alice", activityCount: 45 },
55 | { user: "Bob", activityCount: 72 },
56 | { user: "Charlie", activityCount: 33 }
57 | ];
58 |
59 | // only use reduce
60 |
61 | let mostActiveUser = userActivity.reduce((maxUser, user) =>
62 | user.activityCount > maxUser.activityCount ? user : maxUser
63 | );
64 |
65 | console.log(mostActiveUser);
66 |
67 |
68 | /*
69 | category-wise bill (Total of food, total of utilities)
70 | */
71 |
72 | let expenses = [
73 | { description : "Groceries" , amount : 50, category : "Food"},
74 | { description : "Electricity Bill", amount : 100, category : "Utilities"},
75 | { description : "Dinner", amount : 30, category : "Food"},
76 | { description : "Internet Bill", amount : 50, category : "Utilities"}
77 | ];
78 |
79 | // This code is static
80 | const expenseReport = expenses.reduce(
81 | (report, expense) => {
82 | report[expense.category] += expense.amount;
83 | return report;
84 | },
85 | {Food : 0, Utilities: 0}
86 | );
87 |
88 | console.log(expenseReport);
89 |
90 |
91 | // Dynamic (if we don't know the categories)
92 | const dynamicExpenseReport = expenses.reduce(
93 | (report, expense) => {
94 | report[expense.category] = (report[expense.category] || 0) + expense.amount;
95 | return report;
96 | },
97 | {}
98 | );
99 |
100 | console.log(dynamicExpenseReport);
101 |
102 | /*
103 |
104 | Find the pending tasks according to thier priority
105 |
106 | */
107 |
108 | let tasks = [
109 | { description: "Write Email", completed: false, priority: 2},
110 | { description: "Send Email", completed: true, priority: 3},
111 | { description: "Prepare presentation", completed: false, priority: 1}
112 | ];
113 |
114 | const pendingSortedTasks = tasks
115 | .filter((task) => !(task.completed))
116 | .sort((a, b) => a.priority - b.priority);
117 |
118 | console.log(pendingSortedTasks);
119 |
120 |
121 | /*
122 |
123 | Find average rating for each movie
124 |
125 | */
126 |
127 | let movieRatings = [
128 | { title: "Movie A", ratings: [4, 5, 3]},
129 | { title: "Movie B", ratings: [5, 5, 4]},
130 | { title: "Movie C", ratings: [3, 4, 2]}
131 | ];
132 |
133 | let averageRatings = movieRatings.map((movie) => {
134 | let sum = movie.ratings.reduce((acc, curr) => acc + curr, 0);
135 | let average = sum/movie.ratings.length;
136 |
137 | return {title: movie.title, averageRatings: average.toFixed(2)};
138 | });
139 |
140 | console.log(averageRatings);
--------------------------------------------------------------------------------
/008-MachineCoding/Polyfills/001-forEach.js:
--------------------------------------------------------------------------------
1 | // Exa: Error: .forEach function does not exist on arr variable
2 |
3 | // How to approach - Understand real signature of funtion
4 |
5 | const arr = [10,20,30];
6 |
7 | const res = arr.forEach(function(value, index){
8 | console.log(`Value at ${index} is ${value}`);
9 | });
10 |
11 | const userFunction = function(value, index){
12 | console.log(`Value: ${value}, Index: ${index}`);
13 | }
14 | const result = arr.forEach(userFunction);
15 |
16 | // console.log(`Returned: ${res}`);
17 |
18 | // Signature:
19 | // parameter for forEach -> function; function parameters -> index, value
20 | // what forEach does? -> calls function for every value
21 | // return -> no return
22 |
23 | // Writing Polyfill for forEach()
24 |
25 | if(!Array.prototype.myForEach){
26 |
27 | Array.prototype.myForEach = function(userFunction){
28 |
29 | const originalArr = this; // Points to current object
30 |
31 | for(let i = 0; i < originalArr.length; i++){
32 | userFunction(originalArr[i], i);
33 | }
34 | }
35 | }
36 |
37 | const myResult = arr.myForEach(userFunction);
--------------------------------------------------------------------------------
/008-MachineCoding/Polyfills/002-map.js:
--------------------------------------------------------------------------------
1 | // Signature:
2 | // parameter -> callback
3 | // return -> new array (with result of work asked to be done by user)
4 | // does not modify original array
5 | // performs specified operation on each element, and push the result of that operation into new array
6 |
7 | const multiplyBy10 = function(value){
8 | return value*10;
9 | }
10 |
11 | const arr = [1, 2, 3];
12 |
13 | const result = arr.map(multiplyBy10);
14 |
15 | console.log(result);
16 |
17 | // Writing pollyfill for map()
18 |
19 | if(!Array.prototype.myMap){
20 |
21 | Array.prototype.myMap = function(userFunction){
22 |
23 | const mapResult = [];
24 |
25 | for(let i = 0; i < this.length; i++){
26 | mapResult.push(userFunction(this[i]));
27 | }
28 |
29 | return mapResult;
30 | }
31 | }
32 |
33 | const myResult = arr.myMap(multiplyBy10);
34 | console.log(myResult);
--------------------------------------------------------------------------------
/008-MachineCoding/Polyfills/003-filter.js:
--------------------------------------------------------------------------------
1 | // Signature:
2 | // Parameter -> callback
3 | // Return -> returns a new array, with only those elements that pass the test
4 | // Functionality -> calls function for every value, and adds current value to the result array if it passes the test (returns true)
5 |
6 |
7 |
8 |
9 | const divisibleBy3 = function(value){
10 | if(value%3 === 0){
11 | return true;
12 | }else{
13 | return false;
14 | }
15 | }
16 |
17 | const arr = [10, 20, 30, 40, 50, 60];
18 |
19 | const result = arr.filter(divisibleBy3);
20 | console.log(result);
21 |
22 | if(!Array.prototype.myFilter){
23 |
24 | Array.prototype.myFilter = function(userFunction){
25 |
26 | const filterResult = [];
27 |
28 | for(let i = 0; i < this.length; i++){
29 | if(userFunction(this[i])){
30 | filterResult.push(this[i]);
31 | }
32 | }
33 |
34 | return filterResult;
35 | }
36 | }
37 |
38 | const myResult = arr.myFilter(divisibleBy3);
39 | console.log(myResult);
--------------------------------------------------------------------------------
/008-MachineCoding/Polyfills/004-reduce.js:
--------------------------------------------------------------------------------
1 | const arr = [1, 2, 3, 4, 5];
2 |
3 | console.log(arr.reduce((accumulator, currentValue) => accumulator + currentValue, 0));
4 | console.log(arr.reduce((accumulator, currentValue) => accumulator + currentValue, 15));
5 | console.log(arr.reduce((accumulator, currentValue) => accumulator + currentValue));
6 |
7 |
8 | if (!Array.prototype.myReduce){
9 |
10 | Array.prototype.myReduce = function(cb, initialValue = undefined){
11 |
12 | let acc = initialValue || this[0];
13 |
14 | let startIndex = initialValue ? 0 : 1;
15 |
16 | for(let i = startIndex; i < this.length; i++){
17 | acc = cb(acc, this[i]);
18 | }
19 |
20 | return acc;
21 | }
22 | }
23 |
24 | console.log(arr.myReduce((acc, curr) => acc + curr, 0));
25 | console.log(arr.myReduce((acc, curr) => acc + curr, 15));
26 | console.log(arr.myReduce((acc, curr) => acc + curr));
--------------------------------------------------------------------------------
/009-Proxy/001-proxy.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | The Proxy object enables you to create a proxy for another object, which can intercept and redefine fundamental operations for that object.
4 |
5 | Syntax:
6 |
7 | const proxy1 = new Proxy(targetObject, {})
8 |
9 | OR
10 |
11 | const handler = {}
12 | const proxy1 = new Proxy(targetObject, handler)
13 |
14 |
15 | - targetObject: the original object which you want to proxy
16 | - handler: an object that defines which opeartaions will pe intercepted and how to redifine intercepted operations
17 |
18 | - get(target, prop){
19 |
20 | }
21 |
22 | - set(target, prop, value){
23 |
24 | }
25 | */
26 |
27 | const user = {
28 | username: "Tony Stark",
29 | age: 50,
30 | password: "123"
31 | };
32 |
33 | // console.log(user.passowrd);
34 |
35 | const proxyUser = new Proxy(user,{
36 |
37 | get(target, prop){
38 | // console.log(target);
39 | // console.log(target[prop]);
40 |
41 | if(prop === "password"){
42 | throw new Error("Access denied");
43 | }
44 |
45 | return target[prop];
46 | }
47 | });
48 |
49 | console.log(proxyUser.password);
--------------------------------------------------------------------------------
/009-Proxy/002-negativeIndexExample.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | Accessing array using negative index
4 |
5 | */
6 |
7 | let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
8 | let nums1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
9 | // console.log(arr[-1]);
10 |
11 | function negativeIndex(arr){
12 |
13 | // function returns new proxy array
14 | return new Proxy (arr, {
15 |
16 | // Accessing property
17 | get(target, prop){
18 |
19 | // Index must be number
20 | const index = Number(prop);
21 |
22 | if(index < 0){
23 | return target[target.length + index];
24 | }
25 |
26 | // handles the case for positive index
27 | return target[index];
28 | },
29 |
30 | // Changing the values
31 | set(target, prop, value){
32 |
33 | // Index must be number
34 | const index = Number(prop);
35 |
36 | if(index < 0){
37 | target[target.length + index] = value;
38 | }else{
39 | // handles the case for positive index
40 | target[index] = value;
41 | }
42 |
43 | // we need to send confirmation
44 | return true;
45 | }
46 |
47 | });
48 |
49 | }
50 |
51 | // console.log(nums[-1]);
52 |
53 | let newNums = negativeIndex(nums); // reference is passed
54 | console.log(newNums[-1]);
55 | console.log(newNums[0]);
56 | console.log(newNums[1]);
57 |
58 |
59 | // Before Update
60 | console.log(nums);
61 | console.log(newNums);
62 |
63 | newNums[-1] = 22;
64 |
65 | // After Update
66 | console.log(nums);
67 | console.log(newNums);
68 |
69 | // Original array is also changed (because reference is passed)
70 |
71 |
72 | let newNums1 = negativeIndex([...nums1]); // copy is created
73 | console.log(newNums1[-1]);
74 | console.log(newNums1[0]);
75 | console.log(newNums1[1]);
76 |
77 | // Before Update
78 | console.log(nums1);
79 | console.log(newNums1);
80 |
81 | newNums1[-1] = 22;
82 |
83 | // After Update
84 | console.log(nums1);
85 | console.log(newNums1);
86 |
87 | // Original array is not changed
--------------------------------------------------------------------------------
/010-ClockProject/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Clock
7 |
8 |
9 |
10 |
11 |
12 |
HH:MM:SS AM
13 |
Loading date ...
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/010-ClockProject/script.js:
--------------------------------------------------------------------------------
1 | function updateClock(){
2 |
3 | const timeElement = document.getElementById("time-container");
4 | const dateElement = document.getElementById("date-container");
5 |
6 | const now = new Date();
7 | // console.log(now);
8 |
9 | const hours = (now.getHours() % 12 || 12);
10 | const minutes = now.getMinutes().toString().padStart(2, "0");
11 | const seconds = now.getSeconds().toString().padStart(2, "0");
12 |
13 | const ampm = (now.getHours() >= 12 ? "PM" : "AM");
14 |
15 | timeElement.textContent = `${hours}:${minutes}:${seconds} ${ampm}`;
16 |
17 | const options = {
18 | weekday: "long",
19 | year: "numeric",
20 | month: "long",
21 | day: "numeric"
22 | };
23 |
24 | dateElement.textContent = now.toLocaleDateString(undefined, options);
25 | }
26 |
27 | setInterval(updateClock, 1000);
28 | updateClock();
--------------------------------------------------------------------------------
/010-ClockProject/style.css:
--------------------------------------------------------------------------------
1 | /* Flush the existing CSS (Reset styles)*/
2 |
3 | * {
4 | margin: 0;
5 | padding: 0;
6 | box-sizing: border-box;
7 | font-family: Arial, sans-serif
8 | }
9 |
10 |
11 | body{
12 | background-color: rgb(78, 74, 74);
13 | height: 100vh; /* Full viewport height */
14 | display: flex; /* Enables flexbox */
15 | justify-content: center ; /* Align children to center on main axis*/
16 | align-items: center; /* Align children to center on cross axis*/
17 | }
18 |
19 | .clock-container{
20 | text-align: center;
21 | background-color: rgb(246, 234, 218);
22 | padding: 50px ;
23 | border-radius: 20px;
24 | box-shadow: 0 8px 30px rgb(25, 25, 25);
25 | }
26 |
27 | #time-container{
28 | font-size: 5rem;
29 | color:rgb(0, 0, 0);
30 | margin-bottom: 10px;
31 | letter-spacing: 3px;
32 | }
33 |
34 | #date-container{
35 | font-size: 1.6rem;
36 | color:rgb(0, 0, 0)
37 | }
--------------------------------------------------------------------------------
/011-Promise/001-Basics/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Document
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/011-Promise/001-Basics/script.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | Promise:
4 |
5 | - The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
6 |
7 | - A Promise is a proxy for a value not necessarily known when the promise is created.
8 |
9 | */
10 |
11 | // fetch() - provided by browser
12 |
13 | // const data = fetch('https://api.freeapi.app/api/v1/public/randomproducts')
14 | // fetch() returns a promise
15 |
16 | // data.then((res) => console.log('Promise fulfilled. Data fetched', data));
17 |
18 | const items = document.getElementById("items");
19 |
20 | fetch("https://api.freeapi.app/api/v1/public/randomproducts")
21 | .then((response) => {
22 | response
23 | .json() // converts JSON result into object and returns a promise
24 | .then((obj) => {
25 | const products = obj.data.data;
26 | console.log(products);
27 | products.forEach((product) => {
28 | const li = document.createElement("li");
29 | li.innerText = product.title;
30 | items.appendChild(li);
31 | });
32 | })
33 | .catch((err) => {
34 | console.log("Error converting JSON");
35 | });
36 | })
37 | .catch((err) => {
38 | console.log("Error: ", err);
39 | })
40 | .finally(() => {
41 | console.log("Finally executed");
42 | });
43 |
--------------------------------------------------------------------------------
/011-Promise/002-PromiseChaining/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Document
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/011-Promise/002-PromiseChaining/script.js:
--------------------------------------------------------------------------------
1 | const items = document.getElementById("items");
2 |
3 | // Promise Chaining
4 |
5 | // Improved readbility
6 |
7 | fetch("https://api.freeapi.app/api/v1/public/randomproducts")
8 | .then((response) => response.json())
9 | .then((obj) => {
10 | const products = obj.data.data;
11 | console.log(products);
12 | products.forEach((product) => {
13 | const li = document.createElement("li");
14 | li.innerText = product.title;
15 | items.appendChild(li);
16 | });
17 | })
18 | .catch((err) => {
19 | console.log("Error: ", err);
20 | })
21 | .finally(() => {
22 | console.log("Finally executed");
23 | });
24 |
--------------------------------------------------------------------------------
/011-Promise/003-CleanCode/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Document
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/011-Promise/003-CleanCode/script.js:
--------------------------------------------------------------------------------
1 | // More cleaner way to write code
2 |
3 | function renderToScreen(obj){
4 | const products = obj.data.data;
5 | console.log(products);
6 | products.forEach((product) => {
7 | const li = document.createElement("li");
8 | li.innerText = product.title;
9 | items.appendChild(li);
10 | });
11 | }
12 |
13 | const items = document.getElementById("items");
14 |
15 | fetch("https://api.freeapi.app/api/v1/public/randomproducts")
16 | .then((response) => response.json())
17 | .then(renderToScreen) // Callback function is called along with the result
18 | .catch((err) => {
19 | console.log("Error: ", err);
20 | })
21 | .finally(() => {
22 | console.log("Finally executed");
23 | });
24 |
--------------------------------------------------------------------------------
/012-Sync-Async-JS/001-syncCode.js:
--------------------------------------------------------------------------------
1 | // Sync Code -> Blocking code
2 | // Async Code -> Non-blocking code
3 |
4 | // Async JS is being used for a long time. Promises were introduced later.
5 | // Assume promises don't exist now.
6 |
7 | // Importing fs module
8 | const fs = require('fs');
9 |
10 | console.log("Starting program");
11 |
12 | // readFileSync('path', 'encoding')
13 |
14 | const content = fs.readFileSync('./hello.txt', 'utf-8');
15 | console.log("File reading successful. Content of file: ", content);
16 |
17 | console.log("End of program");
18 |
19 | // This is a blocking code
20 | // Assume, that reading file is a time intensive task and takes 10s for each request
21 | // If we have multiple users, time taken to serve the request will increase as users increase
22 |
--------------------------------------------------------------------------------
/012-Sync-Async-JS/002-asyncCode.js:
--------------------------------------------------------------------------------
1 | // Since we assumed promises don't exist. How do we write asynchronous code?
2 | // Solution: Using callback functions
3 |
4 | // load((f_content) => {do_anything_with_file_content})
5 | // Execute the load function. Whenever the work is done, execute callback
6 |
7 | const fs = require('fs');
8 |
9 | console.log("Starting program");
10 |
11 | // readFile('path', 'encoding', callbackFunction)
12 |
13 | fs.readFile('./hello.txt', 'utf-8', function(err, content){
14 | if(err){
15 | console.log("Error in file reading", err);
16 | } else {
17 | console.log("File reading successful. Content of file: ", content);
18 | }
19 | });
20 |
21 | console.log("End of program");
--------------------------------------------------------------------------------
/012-Sync-Async-JS/003-sumSync.js:
--------------------------------------------------------------------------------
1 | // Now let us assume sum is an intensive task
2 |
3 | console.log("Starting program");
4 |
5 | const result = sum(2, 5);
6 | console.log("Result is ", result);
7 |
8 | // // Assume there were 10M lines of code here, but they won't be executed and will have to wait for result (blocked)
9 | console.log("End of program");
10 |
11 | function sum(a, b){
12 | return a + b;
13 | }
14 |
--------------------------------------------------------------------------------
/012-Sync-Async-JS/004-sumAsync.js:
--------------------------------------------------------------------------------
1 | // Now let us assume sum is an intensive task. Let's simulate time by setTimeout(). Let's try to make it asynchronous.
2 |
3 | console.log("Stating program");
4 |
5 | const result = sum(2, 5, (result) => {
6 | console.log("Result is ", result);
7 | });
8 |
9 | // Assume there were 10M lines of code here, still they will be executed and don't have to wait for result
10 | console.log("End of program");
11 |
12 |
13 | function sum(a, b, cb){
14 | setTimeout(() => {
15 | cb(a+b);
16 | }, 5 * 1000);
17 | }
--------------------------------------------------------------------------------
/012-Sync-Async-JS/005-callbackHell.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | 1. Read contents from file hello.txt
4 | 2. Then create a new file named as backup.txt
5 | 3. Copy contents of hello.txt file to backup.txt file
6 | 4. Delete hello.txt file
7 |
8 | */
9 |
10 | const fs = require('fs');
11 |
12 | console.log("Starting program");
13 |
14 | fs.readFile('hello.txt', 'utf-8', function(err, content){
15 | if(err){
16 | console.log("Error in reading file", err);
17 | } else {
18 | console.log("File reading sucessful. Content of file: ", content);
19 | fs.writeFile('backup.txt', content, function(err){
20 | if(err){
21 | console.log("Error in writing backup.txt", err);
22 | } else {
23 | console.log("backup.txt created successfully");
24 | fs.unlink('hello.txt', function(err){
25 | if(err){
26 | console.log("Error in deleting file", err);
27 | } else {
28 | console.log("File deleted successfully");
29 | }
30 | })
31 | }
32 | })
33 | }
34 | })
35 |
36 | console.log("End of program");
--------------------------------------------------------------------------------
/012-Sync-Async-JS/006-fs-promises.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | 1. Read contents from file hello.txt
4 | 2. Then create a new file named as backup.txt
5 | 3. Copy contents of hello.txt file to backup.txt file
6 | 4. Delete hello.txt file
7 |
8 | */
9 |
10 | const fs = require("fs/promises");
11 |
12 | console.log("Starting program");
13 |
14 | fs
15 | .readFile('hello.txt', 'utf-8')
16 | .then((content) => fs.writeFile('backup.txt', content))
17 | .then(() => fs.unlink('hello.txt'))
18 | .catch((err) => console.log("Error: ", err));
19 |
20 | console.log("End of program");
--------------------------------------------------------------------------------
/012-Sync-Async-JS/007-promisification.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | 1. Read contents from file hello.txt
4 | 2. Then create a new file named as backup.txt
5 | 3. Copy contents of hello.txt file to backup.txt file
6 | 4. Delete hello.txt file
7 |
8 | */
9 |
10 | // Assume 'fs/promises' does not exist. Then how we convert legacy code to modern promisified code
11 |
12 | const fs = require('fs');
13 |
14 | console.log("Starting program");
15 |
16 |
17 | function readFileWithPromise(filepath, encoding){
18 |
19 | return new Promise((resolve, reject) => {
20 | fs.readFile(filepath, encoding, (err, content) => {
21 |
22 | if (err){
23 | reject(err); // If promise is rejected, reject signals to execute catch() function
24 | } else {
25 | resolve(content); // If promise if fulfilled, resolve signals to execute then() function
26 | }
27 | })
28 | })
29 | }
30 |
31 | function writeFileWithPromise(targetFilePath, content){
32 |
33 | return new Promise((resolve, reject) => {
34 | fs.writeFile(targetFilePath, content, (err) => {
35 | if(err){
36 | reject(err);
37 | } else {
38 | resolve()
39 | }
40 | })
41 | })
42 | }
43 |
44 | function unlinkFileWithPromise(filepath){
45 |
46 | return new Promise((resolve, reject) => {
47 | fs.unlink(filepath, (err) => {
48 | if(err){
49 | reject(err);
50 | } else {
51 | resolve();
52 | }
53 | })
54 | })
55 | }
56 |
57 | // const result = readFileWithPromise('hello.txt', 'utf-8');
58 | // result has a promise
59 |
60 | // result.then(
61 | // e => {
62 | //
63 | // }
64 | // ) -> when promise is fulfilled
65 |
66 | readFileWithPromise('hello.txt', 'utf-8')
67 | .then((content) => writeFileWithPromise('backup.txt', content))
68 | .then(() => unlinkFileWithPromise('hello.txt'))
69 | .catch((e) => console.log("Error: ", e))
70 | .finally(() => console.log("All done!"));
71 |
72 | console.log("End of program");
--------------------------------------------------------------------------------
/012-Sync-Async-JS/008-async-await.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | async and await in JavaScript is used
4 | to simplify handling asynchronous operations using promises.
5 |
6 | By enabling asynchronous code to appear synchronous,
7 | they enhance code readability and
8 | make it easier to manage complex asynchronous flows.
9 |
10 | (Syntax Sugar)
11 |
12 | */
13 |
14 | /*
15 |
16 | 1. Read contents from file hello.txt
17 | 2. Then create a new file named as backup.txt
18 | 3. Copy contents of hello.txt file to backup.txt file
19 | 4. Delete hello.txt file
20 |
21 | */
22 |
23 | const fs = require('fs');
24 |
25 | console.log("Starting program");
26 |
27 |
28 | function readFileWithPromise(filepath, encoding){
29 |
30 | return new Promise((resolve, reject) => {
31 | fs.readFile(filepath, encoding, (err, content) => {
32 |
33 | if (err){
34 | reject(err); // If promise is rejected, reject signals to execute catch() function
35 | } else {
36 | resolve(content); // If promise if fulfilled, resolve signals to execute then() function
37 | }
38 | })
39 | })
40 | }
41 |
42 | function writeFileWithPromise(targetFilePath, content){
43 |
44 | return new Promise((resolve, reject) => {
45 | fs.writeFile(targetFilePath, content, (err) => {
46 | if(err){
47 | reject(err);
48 | } else {
49 | resolve()
50 | }
51 | })
52 | })
53 | }
54 |
55 | function unlinkFileWithPromise(filepath){
56 |
57 | return new Promise((resolve, reject) => {
58 | fs.unlink(filepath, (err) => {
59 | if(err){
60 | reject(err);
61 | } else {
62 | resolve();
63 | }
64 | })
65 | })
66 | }
67 |
68 |
69 | // Multiple async code is running in sync fashion
70 |
71 | // readFileWithPromise('hello.txt', 'utf-8')
72 | // .then((content) => writeFileWithPromise('backup.txt', content))
73 | // .then(() => unlinkFileWithPromise('hello.txt'))
74 | // .catch((e) => console.log("Error: ", e))
75 | // .finally(() => console.log("All done!"));
76 |
77 | // console.log("End of program");
78 |
79 |
80 | // const result = readFileWithPromise('hello.txt', 'utf-8');
81 | // result has a promise
82 |
83 |
84 | // const fileContent = await readFileWithPromise('hello.txt', 'utf-8');
85 | // await resolves the promise and returns result of function to fileContent
86 |
87 |
88 | // Whenever we want to use await, we have to write it into an async function
89 |
90 | async function doTasks(){
91 |
92 | try{
93 | const fileContent = await readFileWithPromise('hello.txt', 'utf-8');
94 | await writeFileWithPromise('backup.txt', fileContent);
95 | await unlinkFileWithPromise('hello.txt');
96 | } catch(e) {
97 | console.log("Error: ", e);
98 | } finally {
99 | console.log("All done by function");
100 | }
101 |
102 | }
103 |
104 | // doTasks() -> returns promise
105 |
106 | doTasks().then(() => console.log("All done!"));
107 |
108 | console.log("End of program");
--------------------------------------------------------------------------------
/012-Sync-Async-JS/009-assignment.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | 1. Read contents from file hello.txt
4 | 2. Then create a new file named as backup.txt
5 | 3. Copy contents of hello.txt file to backup.txt file
6 | 4. Wait for 10 secs
7 | 5. Delete hello.txt file
8 |
9 | */
10 |
11 | const fs = require('fs');
12 |
13 | console.log("Starting program");
14 |
15 | function readFileWithPromise(filepath, encoding){
16 |
17 | return new Promise((resolve, reject) => {
18 | fs.readFile(filepath, encoding, (err, content) => {
19 | if(err){
20 | reject(err);
21 | } else {
22 | resolve(content);
23 | }
24 | });
25 | });
26 | }
27 |
28 | function writeFileWithPromise(targetFilePath, content){
29 |
30 | return new Promise((resolve, reject) => {
31 | fs.writeFile(targetFilePath, content, (err) => {
32 | if(err){
33 | reject(err);
34 | } else {
35 | resolve()
36 | }
37 | });
38 | });
39 | }
40 |
41 | function unlinkFileWithPromise(filepath){
42 |
43 | return new Promise((resolve, reject) => {
44 | fs.unlink(filepath, (err) => {
45 | if(err){
46 | reject(err);
47 | } else {
48 | resolve();
49 | }
50 | });
51 | });
52 | }
53 |
54 | function wait(seconds){
55 |
56 | return new Promise((resolve, reject) => {
57 | setTimeout(() => resolve(), seconds * 1000);
58 | });
59 | }
60 |
61 | async function doTasks(){
62 |
63 | try{
64 | const fileContent = await readFileWithPromise('hello.txt', 'utf-8');
65 | await writeFileWithPromise('backup.txt', fileContent);
66 | await wait(10);
67 | await unlinkFileWithPromise('hello.txt');
68 | } catch (e) {
69 | console.log("Error: ", e);
70 | } finally {
71 | console.log("All done by function");
72 | }
73 |
74 | }
75 |
76 | doTasks().then(() => console.log("All done!"));
77 |
78 | console.log("End of program");
79 |
--------------------------------------------------------------------------------
/013-LexicalScoping-ClosureFunctions/001-lexicalScope-closureFunction.js:
--------------------------------------------------------------------------------
1 | // Use debugger with this code to understand this
2 |
3 | /*
4 | Lexical Scope:
5 | - A convention that how determinses how variables are accessible in block of code
6 | - It is based on the physical location of variables and code blocks in the source code
7 | - It is determined when the code is created, not when it's run
8 | - Inner functions can use variables from outer functions they're inside in
9 |
10 | Closure Function:
11 | - A closure function is a function that has access to the variables of its outer function,
12 | even after the outer function has finished its execution
13 | - It is basically a function that is binded by its lexical scope
14 | */
15 |
16 | let fname = "Tony";
17 | let team = "Avengers";
18 |
19 | // let fname = "Bruce";
20 | // cannot re-declare block-scoped variable 'fname'
21 |
22 | function sayName(){
23 | let fname = "Bruce";
24 | let lname = "Fury";
25 |
26 | // JS will check if fname exists in the memory phase of its FEC
27 | // If not found it checks with [[Scope of Parent]]
28 | console.log("Inside of sayName fn the value of fname is ", fname);
29 | console.log("Inside of sayName", fname, " ", lname);
30 |
31 |
32 | function inner(){
33 | console.log("Inside inner fn", fname, " ", lname, " ", team);
34 | return;
35 | }
36 |
37 | inner();
38 | }
39 |
40 | console.log("Value of fname is ", fname);
41 | sayName();
42 |
43 | // How any variable is read in function
44 | // - Checks in local (Function Execution Context) memory phase
45 | // - If not found, check in its parent
46 | // - If not found, check in its parent
47 | // .
48 | // .
49 | // .
50 | // - Till scope of GEC
--------------------------------------------------------------------------------
/013-LexicalScoping-ClosureFunctions/002-counter.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | - I should have a fn increment()
4 | - On call of the function it should increment the number
5 | - and return current counter
6 |
7 | - console.log( increment() ); 1
8 | - console.log( increment() ); 2
9 | - console.log( increment() ); 3
10 | - console.log( increment() ); 4
11 |
12 | */
13 |
14 |
15 | let count = 0;
16 |
17 | function increment(){
18 | count++;
19 | return count;
20 | }
21 |
22 | console.log(increment()); // 1
23 | console.log(increment()); // 2
24 | console.log(increment()); // 3
25 |
26 | count = -100; // Someone else who neeeded count, reassigned it
27 |
28 | console.log(increment()); // -99
29 | console.log(increment()); // -98
30 | console.log(increment()); // -97
31 |
32 | // How do we resolve the above problem ?
33 |
34 |
35 |
36 | // function test(){
37 | // let x = 10;
38 | // x++;
39 | // return x;
40 | // }
41 |
42 | // console.log(test()); // 11
43 | // console.log(test()); // 11
44 | // console.log(test()); // 11
45 | // console.log(test()); // 11
46 |
47 |
48 | function test() {
49 | let x = 10;
50 |
51 | function increment(){
52 | x++;
53 | return x;
54 | }
55 |
56 | return increment;
57 | }
58 |
59 | const f = test();
60 | const g = test();
61 |
62 | console.log(f()); // 11
63 | console.log(f()); // 12
64 | console.log(f()); // 13
65 | console.log(f()); // 14
66 | console.log(g()); // 11
67 | console.log(g()); // 12
68 |
69 |
70 | // This is a good example of Encapsulation
71 |
72 | function increment1(){
73 | let count = 0;
74 |
75 | return function(){
76 | count++;
77 | return count;
78 | }
79 | }
80 |
81 | console.log(increment1()()); // 1
82 | console.log(increment1()()); // 1
83 | console.log(increment1()()); // 1
84 | console.log(increment1()()); // 1
85 | console.log(increment1()()); // 1
86 |
87 | let x = increment1();
88 | let y = increment1();
89 |
90 | console.log(x()); // 1
91 | console.log(x()); // 2
92 | console.log(y()); // 1
93 | console.log(x()); // 3
94 | console.log(x()); // 4
95 | console.log(y()); // 2
96 | console.log(x()); // 5
97 |
98 |
99 |
100 | function createCounter(stepSize = 1, initialValue = 0){
101 |
102 | return function(){
103 | initialValue += stepSize;
104 | return initialValue;
105 | }
106 | }
107 |
108 | const a = createCounter(3, 10);
109 | console.log(a()); // 13
110 | console.log(a()); // 16
111 | console.log(a()); // 19
112 |
--------------------------------------------------------------------------------
/013-LexicalScoping-ClosureFunctions/003-memoryLeak-Closure.js:
--------------------------------------------------------------------------------
1 | function createInstance(){
2 |
3 | let store = {
4 | value : 100
5 | }; // Assume this object is of 100 MB
6 |
7 | return function(){
8 | console.log(store);
9 | };
10 | }
11 |
12 | const logger = createInstance();
13 |
14 | logger();
15 | logger();
16 | logger();
17 |
18 | // Assume there is 1 Million line of code here,
19 | // and we don't need to use logger in this code or in further lines
20 |
21 | // Assume this 1 Million line of code runs for next 20 days
22 | // So our 100 MB will still be occupied
23 |
24 | // After we finish using logger, we can set it to null or undefined, this will dereference
25 | logger = null;
26 |
27 | // If you need it further, don't make it null
--------------------------------------------------------------------------------
/014-Debouncing/debounce.js:
--------------------------------------------------------------------------------
1 | /*
2 | Debouncing, means to discard operations that occur too close together during a specific interval,
3 | and consolidate them into a single invocation.
4 | */
5 |
6 | function debounce(fn, delay){
7 |
8 | // console.log(arguments);
9 |
10 | let myId;
11 |
12 | return function(...args){
13 |
14 | // pass the timeoutID to cancel the timeout
15 | clearTimeout(myId);
16 |
17 | // store the timeoutID (+ve integer) -> to identify timer created by the call to setTimeout()
18 | myId = setTimeout(() => {
19 | fn.apply(this, args);
20 | }, delay);
21 | };
22 | }
23 |
24 | function greet(name){
25 | console.log(`Hello ${name}`);
26 | }
27 |
28 | const debouncedGreet = debounce(() => greet("Tony"), 3000);
29 | debouncedGreet();
30 | debouncedGreet();
31 | debouncedGreet();
32 | debouncedGreet();
33 | debouncedGreet();
34 | debouncedGreet();
--------------------------------------------------------------------------------
/014-Debouncing/debounce.md:
--------------------------------------------------------------------------------
1 | ### Debouncing
2 |
3 | 
4 |
5 | - [Diagram source](https://dev.to/jeetvora331/javascript-debounce-easiest-explanation--29hc)
6 | - [Diagram credits](https://dev.to/jeetvora331)
7 |
--------------------------------------------------------------------------------
/015-Throttling/throttling.js:
--------------------------------------------------------------------------------
1 | function throttle(fn, delay){
2 |
3 | let myId = null;
4 |
5 | return function(...args){
6 |
7 | if(myId === null){
8 | fn(...args);
9 |
10 | myId = setTimeout(() => {
11 | myId = null;
12 | }, delay);
13 | }
14 | }
15 | }
16 |
17 | function greet(name){
18 | console.log(`Hello ${name}`);
19 | }
20 |
21 | const throttledGreet = throttle(() => greet("Tony"), 3000);
22 | throttledGreet();
23 | throttledGreet();
24 | throttledGreet();
25 | throttledGreet();
26 | throttledGreet();
27 |
28 | // setTimeout(() => throttledGreet(), 2000);
29 | // setTimeout(() => throttledGreet(), 3000);
30 |
--------------------------------------------------------------------------------
/015-Throttling/throttling.md:
--------------------------------------------------------------------------------
1 | ### Throttling
2 |
3 | 
4 |
5 | - [Diagram source]([https://dev.to/jeetvora331/javascript-debounce-easiest-explanation--29hc](https://dev.to/jeetvora331/throttling-in-javascript-easiest-explanation-1081))
6 | - [Diagram credits](https://dev.to/jeetvora331)
7 |
--------------------------------------------------------------------------------
/016-CodeChallenges/001-P0/p0-challenge-01.js:
--------------------------------------------------------------------------------
1 | function totalCupcakes(trayOne, trayTwo) {
2 |
3 | return trayOne + trayTwo;
4 |
5 | }
6 |
--------------------------------------------------------------------------------
/016-CodeChallenges/001-P0/p0-challenge-02.js:
--------------------------------------------------------------------------------
1 | function remainingApples(totalApples, givenAway) {
2 |
3 | return totalApples - givenAway;
4 |
5 | }
6 |
--------------------------------------------------------------------------------
/016-CodeChallenges/001-P0/p0-challenge-03.js:
--------------------------------------------------------------------------------
1 | function totalChocolateBars(barsPerBox, numberOfBoxes) {
2 |
3 | return barsPerBox*numberOfBoxes;
4 |
5 | }
--------------------------------------------------------------------------------
/016-CodeChallenges/002-Conditionals/challenge-01.js:
--------------------------------------------------------------------------------
1 | // You just need to implement the checkEvenOdd function
2 | function checkEvenOdd(num) {
3 | // Return "Even" if num is even, otherwise return "Odd"
4 | if (num % 2 === 0) {
5 | return "Even";
6 | } else {
7 | return "Odd";
8 | }
9 | }
--------------------------------------------------------------------------------
/016-CodeChallenges/002-Conditionals/challenge-02.js:
--------------------------------------------------------------------------------
1 | // You just need to implement the findLargest function
2 | function findLargest(a, b, c) {
3 | // Return the largest among a, b, and c
4 | if (a > b) {
5 | if (a > c) {
6 | return a;
7 | } else {
8 | return c;
9 | }
10 | } else {
11 | if (b > c) {
12 | return b;
13 | } else {
14 | return c;
15 | }
16 | }
17 | }
--------------------------------------------------------------------------------
/016-CodeChallenges/002-Conditionals/challenge-03.js:
--------------------------------------------------------------------------------
1 | // You just need to implement the checkVotingEligibility function
2 | function checkVotingEligibility(age) {
3 | // Return "Eligible" if age is 18 or more, otherwise return "Not Eligible"
4 | if (age >= 18) {
5 | return "Eligible";
6 | } else {
7 | return "Not Eligible";
8 | }
9 | }
--------------------------------------------------------------------------------
/016-CodeChallenges/002-Conditionals/challenge-04.js:
--------------------------------------------------------------------------------
1 | // You just need to implement the calculateGrade function
2 | function calculateGrade(marks) {
3 | // Return grade based on the marks
4 | if (marks >= 90) {
5 | return "A";
6 | } else if (marks >= 80) {
7 | return "B";
8 | } else if (marks >= 70) {
9 | return "C";
10 | } else if (marks >= 60) {
11 | return "D";
12 | } else {
13 | return "F";
14 | }
15 | }
--------------------------------------------------------------------------------
/016-CodeChallenges/002-Conditionals/challenge-05.js:
--------------------------------------------------------------------------------
1 | // You just need to implement the isLeapYear function
2 | function isLeapYear(year) {
3 | // Return "Leap Year" if the year is a leap year, otherwise return "Not a Leap Year"
4 | if (year % 4 === 0) {
5 | if (year % 100 === 0 && year % 400 != 0) {
6 | return "Not a Leap Year";
7 | } else {
8 | return "Leap Year";
9 | }
10 | } else {
11 | return "Not a Leap Year";
12 | }
13 | }
--------------------------------------------------------------------------------
/016-CodeChallenges/002-Conditionals/challenge-06.js:
--------------------------------------------------------------------------------
1 | // You just need to implement the trafficLightAction function
2 | function trafficLightAction(color) {
3 | // Return "Stop", "Slow Down", or "Go" based on the traffic light color
4 | switch (color.toLowerCase()) {
5 | case "red":
6 | return "Stop";
7 | case "yellow":
8 | return "Slow Down";
9 | case "green":
10 | return "Go";
11 | default:
12 | return "Invalid Color";
13 | }
14 | }
--------------------------------------------------------------------------------
/016-CodeChallenges/002-Conditionals/challenge-07.js:
--------------------------------------------------------------------------------
1 | // You just need to implement the getDayOfWeek function
2 | function getDayOfWeek(day) {
3 | // Return the corresponding day of the week based on the input number
4 | switch (day) {
5 | case 1:
6 | return "Monday";
7 | case 2:
8 | return "Tuesday";
9 | case 3:
10 | return "Wednesday";
11 | case 4:
12 | return "Thursday";
13 | case 5:
14 | return "Friday";
15 | case 6:
16 | return "Saturday";
17 | case 7:
18 | return "Sunday";
19 | default:
20 | return "Invalid Day";
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/016-CodeChallenges/002-Conditionals/challenge-08.js:
--------------------------------------------------------------------------------
1 | // You just need to implement the checkNumberType function
2 | function checkNumberType(num) {
3 | // Return "Positive", "Negative", or "Zero" based on the input number
4 | if (num > 0) {
5 | return "Positive";
6 | } else if (num < 0) {
7 | return "Negative";
8 | } else {
9 | return "Zero";
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/016-CodeChallenges/002-Conditionals/challenge-09.js:
--------------------------------------------------------------------------------
1 | // You just need to implement the convertTemperature function
2 | function convertTemperature(value, scale) {
3 | // Convert temperature based on the scale ("C" to "F" or "F" to "C")
4 | let temp = null;
5 | let result;
6 | switch (scale) {
7 | case "C":
8 | temp = (1.8 * value + 32).toString();
9 | temp = temp.concat("\u00B0F");
10 | break;
11 | case "F":
12 | temp = ((value - 32) / 1.8).toString();
13 | temp = temp.concat("\u00B0C");
14 | break;
15 | }
16 | return temp;
17 | }
--------------------------------------------------------------------------------
/016-CodeChallenges/002-Conditionals/challenge-10.js:
--------------------------------------------------------------------------------
1 | // You just need to implement the calculator function
2 | function calculator(num1, num2, operator) {
3 | // Perform basic arithmetic operations using switch case
4 | switch (operator) {
5 | case "+":
6 | return num1 + num2;
7 | case "-":
8 | return num1 - num2;
9 | case "*":
10 | return num1 * num2;
11 | case "/":
12 | if (num2 === 0) {
13 | return "Cannot divide by zero";
14 | } else {
15 | return num1 / num2;
16 | }
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/016-CodeChallenges/003-Loops/challenge-01.js:
--------------------------------------------------------------------------------
1 | // You just need to implement the distributeGifts function
2 | function distributeGifts(totalGifts, friends) {
3 |
4 | if (totalGifts <= friends) {
5 | return totalGifts;
6 | } else {
7 | return friends;
8 | }
9 | }
--------------------------------------------------------------------------------
/016-CodeChallenges/003-Loops/challenge-02.js:
--------------------------------------------------------------------------------
1 | // You just need to implement the countApples function
2 | function countApples(apples) {
3 | return apples;
4 | }
5 |
--------------------------------------------------------------------------------
/016-CodeChallenges/003-Loops/challenge-03.js:
--------------------------------------------------------------------------------
1 | // You just need to implement the countBoxes function
2 | function countBoxes(totalBars, barsPerBox) {
3 | return Math.floor(totalBars / barsPerBox);
4 | }
--------------------------------------------------------------------------------
/016-CodeChallenges/003-Loops/challenge-04.js:
--------------------------------------------------------------------------------
1 | // You just need to implement the totalWater function
2 | function totalWater(waterAmounts) {
3 | let totalAmount = 0;
4 |
5 | for (let i = 0; i < waterAmounts.length; i++) {
6 | totalAmount = totalAmount + waterAmounts[i];
7 | }
8 |
9 | return totalAmount;
10 | }
--------------------------------------------------------------------------------
/016-CodeChallenges/003-Loops/challenge-05.js:
--------------------------------------------------------------------------------
1 | // You just need to implement the countSteps function
2 | function countSteps(targetSteps) {
3 | let count = 0;
4 | for (let i = 1; i <= targetSteps; i++) {
5 | count++;
6 | }
7 | return count;
8 | }
--------------------------------------------------------------------------------
/016-CodeChallenges/003-Loops/challenge-06.js:
--------------------------------------------------------------------------------
1 | // You just need to implement the workingDays function
2 | function workingDays(days) {
3 | let count = 0;
4 |
5 | for (let i = 0; i < days.length; i++) {
6 | if (days[i] === "Saturday" || days[i] === "Sunday") {
7 | continue;
8 | } else {
9 | count++;
10 | }
11 | }
12 |
13 | return count;
14 | }
--------------------------------------------------------------------------------
/016-CodeChallenges/003-Loops/challenge-07.js:
--------------------------------------------------------------------------------
1 | // You just need to implement the totalStars function
2 | function totalStars(starLevels) {
3 | let count = 0;
4 | for (let i = 0; i < starLevels.length; i++) {
5 | count = count + starLevels[i].length;
6 | }
7 | return count;
8 | }
--------------------------------------------------------------------------------
/016-CodeChallenges/003-Loops/challenge-08.js:
--------------------------------------------------------------------------------
1 | // You just need to implement the totalPrice function
2 | function totalPrice(prices) {
3 | let total = 0;
4 |
5 | for (let i = 0; i < prices.length; i++) {
6 | total = total + prices[i];
7 | }
8 |
9 | return total;
10 | }
--------------------------------------------------------------------------------
/016-CodeChallenges/003-Loops/challenge-09.js:
--------------------------------------------------------------------------------
1 | function shinyDiamondRug(n) {
2 | let pattern = "";
3 |
4 | let p1_rows = n,
5 | p2_rows = n - 1;
6 |
7 | for (let i = 1; i <= p1_rows; i++) {
8 | //spaces
9 | for (let j = 1; j <= p1_rows - i; j++) {
10 | pattern += " ";
11 | }
12 |
13 | //stars
14 | for (let j = 1; j <= 2 * i - 1; j++) {
15 | pattern += "*";
16 | }
17 |
18 | //newline
19 | pattern += "\n";
20 | }
21 |
22 | for (let i = 1; i <= p2_rows; i++) {
23 | //spaces
24 | for (let j = 1; j <= i; j++) {
25 | pattern += " ";
26 | }
27 |
28 | //stars
29 | for (let j = 1; j <= 2 * (p2_rows - i) + 1; j++) {
30 | pattern += "*";
31 | }
32 |
33 | //newline
34 | if (i != p2_rows) {
35 | pattern += "\n";
36 | }
37 | }
38 |
39 | return pattern;
40 | }
--------------------------------------------------------------------------------
/016-CodeChallenges/003-Loops/challenge-10.js:
--------------------------------------------------------------------------------
1 | function invertedMountain(n) {
2 | let res = "",
3 | flag = 0,
4 | str = "*";
5 | for (let i = n; i >= 1; i--) {
6 | res += str.repeat(i);
7 | if (i == 1) {
8 | flag = 1;
9 | }
10 | if (flag != 1) {
11 | res += "\n";
12 | }
13 | }
14 | return res;
15 | }
16 |
--------------------------------------------------------------------------------
/016-CodeChallenges/004-Arrays/challenge-01.js:
--------------------------------------------------------------------------------
1 | // You just need to implement the addGuest function
2 | function addGuest(guestList, newGuest) {
3 | // Add the newGuest to guestList and return the updated list
4 | guestList.push(newGuest);
5 | return guestList;
6 | }
7 |
--------------------------------------------------------------------------------
/016-CodeChallenges/004-Arrays/challenge-02.js:
--------------------------------------------------------------------------------
1 | // You just need to implement the eatCandy function
2 | function eatCandy(candyJar) {
3 | // Remove the last candy from the jar and return the updated jar
4 | candyJar.pop();
5 | return candyJar;
6 | }
--------------------------------------------------------------------------------
/016-CodeChallenges/004-Arrays/challenge-03.js:
--------------------------------------------------------------------------------
1 | // You just need to implement the addPuppy function
2 | function addPuppy(queue, puppyName) {
3 | // Add puppyName at the beginning of queue and return updated queue
4 | queue.unshift(puppyName);
5 | return queue;
6 | }
7 |
--------------------------------------------------------------------------------
/016-CodeChallenges/004-Arrays/challenge-04.js:
--------------------------------------------------------------------------------
1 | // You just need to implement the removeStudent function
2 | function removeStudent(bus) {
3 | // Remove the first student and return the updated bus list
4 | bus.shift();
5 | return bus;
6 | }
--------------------------------------------------------------------------------
/016-CodeChallenges/004-Arrays/challenge-05.js:
--------------------------------------------------------------------------------
1 | // You just need to implement the sortBooks function
2 | function sortBooks(books) {
3 | // Sort the books alphabetically and return the updated list
4 | books.sort();
5 | return books;
6 | }
--------------------------------------------------------------------------------
/016-CodeChallenges/004-Arrays/challenge-06.js:
--------------------------------------------------------------------------------
1 | // You just need to implement the filterHealthy function
2 | function filterHealthy(foodList) {
3 | // Remove unhealthy food and return updated list
4 | let newlist = [];
5 |
6 | for (let i = 0; i < foodList.length; i++) {
7 | if (foodList[i] != "Burger") {
8 | newlist.push(foodList[i]);
9 | }
10 | }
11 |
12 | return newlist;
13 | }
--------------------------------------------------------------------------------
/016-CodeChallenges/004-Arrays/challenge-07.js:
--------------------------------------------------------------------------------
1 | // You just need to implement the findPhone function
2 | function findPhone(items) {
3 | // Return the index of "Phone" in the items array
4 | return items.indexOf("Phone");
5 | }
--------------------------------------------------------------------------------
/016-CodeChallenges/004-Arrays/challenge-08.js:
--------------------------------------------------------------------------------
1 | // You just need to implement the writeLoveLetter function
2 | function writeLoveLetter(message, name) {
3 | // Add name at the start of the message and return updated array
4 | message.unshift(name);
5 | return message;
6 | }
--------------------------------------------------------------------------------
/016-CodeChallenges/004-Arrays/challenge-09.js:
--------------------------------------------------------------------------------
1 | // You just need to implement the addVIP function
2 | function addVIP(queue, vipGuest) {
3 | // Add vipGuest at the beginning of queue and return updated queue
4 | queue.unshift(vipGuest);
5 | return queue;
6 | }
--------------------------------------------------------------------------------
/016-CodeChallenges/004-Arrays/challenge-10.js:
--------------------------------------------------------------------------------
1 | // You just need to implement the countMovies function
2 | function countMovies(movieList) {
3 | // Return the number of movies in the movieList
4 | let number = movieList.length;
5 | return number;
6 | }
--------------------------------------------------------------------------------
/016-CodeChallenges/005-Prototypes/challenge-01.js:
--------------------------------------------------------------------------------
1 | // You need to implement the Animal constructor function and its prototype method
2 |
3 | function Animal(name) {
4 | // Initialize name property
5 | this.name = name;
6 | }
7 |
--------------------------------------------------------------------------------
/016-CodeChallenges/005-Prototypes/challenge-02.js:
--------------------------------------------------------------------------------
1 | // You need to implement the Robot constructor function and its prototype method
2 |
3 | function Robot(name, batteryLevel) {
4 | // Initialize name and batteryLevel properties
5 | this.name = name;
6 | this.batteryLevel = batteryLevel;
7 | }
8 |
9 | // Define charge method on Robot's prototype
10 | if (!Robot.prototype.charge) {
11 | Robot.prototype.charge = function () {
12 | if (this.batteryLevel + 20 <= 100) {
13 | this.batteryLevel += 20;
14 | return this.batteryLevel;
15 | } else {
16 | this.batteryLevel = 100;
17 | return this.batteryLevel;
18 | }
19 | };
20 | }
21 |
--------------------------------------------------------------------------------
/016-CodeChallenges/005-Prototypes/challenge-03.js:
--------------------------------------------------------------------------------
1 | // You need to implement the Counter constructor function and its prototype methods
2 |
3 | function Counter() {
4 | // Initialize count property
5 | this.count = 0;
6 | }
7 |
8 | // Define increment method on Counter's prototype
9 | if (!Counter.prototype.increment) {
10 | Counter.prototype.increment = function () {
11 | this.count += 1;
12 | return this.count;
13 | };
14 | }
15 |
16 | // Define decrement method on Counter's prototype
17 | if (!Counter.prototype.decrement) {
18 | Counter.prototype.decrement = function () {
19 | this.count -= 1;
20 | return this.count;
21 | };
22 | }
23 |
--------------------------------------------------------------------------------
/016-CodeChallenges/005-Prototypes/challenge-04.js:
--------------------------------------------------------------------------------
1 | // You need to implement the Playlist constructor function and its prototype method
2 |
3 | function Playlist() {
4 | // Initialize songs property
5 | this.songs = [];
6 | }
7 |
8 | // Define addSong method on Playlist's prototype
9 | if (!Playlist.prototype.addSong) {
10 | Playlist.prototype.addSong = function (song) {
11 | this.songs.push(song);
12 | };
13 | }
14 |
--------------------------------------------------------------------------------
/016-CodeChallenges/005-Prototypes/challenge-05.js:
--------------------------------------------------------------------------------
1 | // You need to implement the ShoppingCart constructor function and its prototype methods
2 |
3 | function ShoppingCart() {
4 | // Initialize items property
5 | this.items = [];
6 | }
7 |
8 | // Define addItem method on ShoppingCart's prototype
9 | if (!ShoppingCart.prototype.addItem) {
10 | ShoppingCart.prototype.addItem = function (price) {
11 | this.items.push(price);
12 | };
13 | }
14 |
15 | // Define getTotalPrice method on ShoppingCart's prototype
16 | if (!ShoppingCart.prototype.getTotalPrice) {
17 | ShoppingCart.prototype.getTotalPrice = function () {
18 | const sum = this.items.reduce(function (accumulator, currentValue) {
19 | return accumulator + currentValue;
20 | }, 0);
21 | return sum;
22 | };
23 | }
24 |
--------------------------------------------------------------------------------
/016-CodeChallenges/005-Prototypes/challenge-06.js:
--------------------------------------------------------------------------------
1 | // You need to implement the BankAccount constructor function and its prototype methods
2 |
3 | function BankAccount(balance) {
4 | // Initialize balance and transactions properties
5 | this.balance = balance;
6 | this.transactions = [];
7 | }
8 |
9 | // Define deposit method on BankAccount's prototype
10 | if (!BankAccount.prototype.deposit) {
11 | BankAccount.prototype.deposit = function (amount) {
12 | this.balance += amount;
13 | this.transactions.push(`Deposited ${amount}`);
14 | };
15 | }
16 |
17 | // Define withdraw method on BankAccount's prototype
18 | if (!BankAccount.prototype.withdraw) {
19 | BankAccount.prototype.withdraw = function (amount) {
20 | if (this.balance - amount < 0) {
21 | this.transactions.push("Insufficient balance");
22 | } else {
23 | this.balance -= amount;
24 | this.transactions.push(`Withdrew ${amount}`);
25 | }
26 | };
27 | }
28 |
29 | // Define getTransactionHistory method on BankAccount's prototype
30 | if (!BankAccount.prototype.getTransactionHistory) {
31 | BankAccount.prototype.getTransactionHistory = function () {
32 | return this.transactions;
33 | };
34 | }
35 |
--------------------------------------------------------------------------------
/016-CodeChallenges/005-Prototypes/challenge-07.js:
--------------------------------------------------------------------------------
1 | // You need to implement the Employee constructor function and its prototype method
2 |
3 | function Employee(name, position, salary) {
4 | // Initialize name, position, and salary properties
5 | this.name = name;
6 | this.position = position;
7 | this.salary = salary;
8 | }
9 |
10 | // Define applyBonus method on Employee's prototype
11 | if (!Employee.prototype.applyBonus) {
12 | Employee.prototype.applyBonus = function (percent) {
13 | this.salary += (percent * this.salary) / 100;
14 | };
15 | }
16 |
--------------------------------------------------------------------------------
/016-CodeChallenges/005-Prototypes/challenge-08.js:
--------------------------------------------------------------------------------
1 | // You need to implement the Library constructor function and its prototype methods
2 |
3 | function Library() {
4 | // Initialize books property
5 | this.books = [];
6 | }
7 |
8 | // Define addBook method on Library's prototype
9 | if (!Library.prototype.addBook) {
10 | Library.prototype.addBook = function (book) {
11 | this.books.push(book);
12 | };
13 | }
14 |
15 | // Define findBook method on Library's prototype
16 | if (!Library.prototype.findBook) {
17 | Library.prototype.findBook = function (title) {
18 | if (this.books.includes(title)) {
19 | return "Book found";
20 | } else {
21 | return "Book not found";
22 | }
23 | };
24 | }
25 |
--------------------------------------------------------------------------------
/016-CodeChallenges/005-Prototypes/challenge-09.js:
--------------------------------------------------------------------------------
1 | // You need to implement the BankAccount constructor function and its prototype methods
2 |
3 | function BankAccount(accountNumber, holderName, balance) {
4 | // Initialize accountNumber, holderName, and balance properties
5 | this.accountNumber = accountNumber;
6 | this.holderName = holderName;
7 | this.balance = balance;
8 | }
9 |
10 | // Define deposit method on BankAccount's prototype
11 | if (!BankAccount.prototype.deposit) {
12 | BankAccount.prototype.deposit = function (amount) {
13 | this.balance += amount;
14 | };
15 | }
16 |
17 | // Define withdraw method on BankAccount's prototype
18 | if (!BankAccount.prototype.withdraw) {
19 | BankAccount.prototype.withdraw = function (amount) {
20 | if (this.balance >= amount) {
21 | this.balance -= amount;
22 | }
23 | };
24 | }
25 |
26 | // Define transfer method on BankAccount's prototype
27 | if (!BankAccount.prototype.transfer) {
28 | BankAccount.prototype.transfer = function (amount, targetAccount) {
29 | if (this.balance >= amount) {
30 | this.balance -= amount;
31 | targetAccount.deposit(amount);
32 | }
33 | };
34 | }
35 |
--------------------------------------------------------------------------------
/016-CodeChallenges/005-Prototypes/challenge-10.js:
--------------------------------------------------------------------------------
1 | // You need to implement the Product constructor function and its prototype methods
2 |
3 | function Product(name, price, stock) {
4 | // Initialize name, price, and stock properties
5 | this.name = name;
6 | this.price = price;
7 | this.stock = stock;
8 | }
9 |
10 | // Define applyDiscount method on Product's prototype
11 | if (!Product.prototype.applyDiscount) {
12 | Product.prototype.applyDiscount = function (percent) {
13 | this.price = Math.round(this.price - (percent * this.price) / 100);
14 | };
15 | }
16 | // Define purchase method on Product's prototype
17 | if (!Product.prototype.purchase) {
18 | Product.prototype.purchase = function (quantity) {
19 | if (this.stock !== 0 && this.stock >= quantity) {
20 | this.stock = this.stock - quantity;
21 | return this.stock;
22 | } else {
23 | return "Not enough stock";
24 | }
25 | };
26 | }
27 |
--------------------------------------------------------------------------------
/016-CodeChallenges/006-Objects/challenge-01.js:
--------------------------------------------------------------------------------
1 | // You just need to implement the createStudentProfile function
2 | function createStudentProfile(name, age, grade) {
3 | // Return an object with name, age, and grade
4 | if (
5 | typeof name !== "string" ||
6 | name === "" ||
7 | typeof age !== "number" ||
8 | age <= 5 ||
9 | typeof grade !== "string"
10 | ) {
11 | return "Invalid input";
12 | } else {
13 | return { name, age, grade };
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/016-CodeChallenges/006-Objects/challenge-02.js:
--------------------------------------------------------------------------------
1 | // You just need to implement the addCarColor function
2 | function addCarColor(car, color) {
3 | // Add color property to the car object
4 | if (
5 | typeof car !== "object" ||
6 | !car.hasOwnProperty("brand") ||
7 | !car.hasOwnProperty("model") ||
8 | typeof color !== "string" ||
9 | color === ""
10 | ) {
11 | return "Invalid color";
12 | }
13 |
14 | car.color = color;
15 |
16 | return car;
17 | }
18 |
--------------------------------------------------------------------------------
/016-CodeChallenges/006-Objects/challenge-03.js:
--------------------------------------------------------------------------------
1 | // You just need to implement the hasDiscount function
2 | function hasDiscount(product) {
3 | // Check if product has discount property
4 | if (typeof product !== "object" || !product.hasOwnProperty("discount")) {
5 | return false;
6 | }
7 |
8 | return true;
9 | }
10 |
--------------------------------------------------------------------------------
/016-CodeChallenges/006-Objects/challenge-04.js:
--------------------------------------------------------------------------------
1 | // You just need to implement the removePassword function
2 | function removePassword(user) {
3 | // Remove password property
4 | if (
5 | typeof user !== "object" ||
6 | user === null ||
7 | !user.hasOwnProperty("username") ||
8 | !user.hasOwnProperty("password")
9 | ) {
10 | return user;
11 | }
12 |
13 | delete user.password;
14 | return user;
15 | }
16 |
--------------------------------------------------------------------------------
/016-CodeChallenges/006-Objects/challenge-05.js:
--------------------------------------------------------------------------------
1 | // You just need to implement the countProperties function
2 | function countProperties(user) {
3 | // Return the number of properties in user
4 | if (
5 | typeof user !== "object" ||
6 | user === null ||
7 | Object.keys(user).length <= 0
8 | ) {
9 | return 0;
10 | }
11 | const arr = Object.keys(user);
12 | return arr.length;
13 | }
14 |
--------------------------------------------------------------------------------
/016-CodeChallenges/006-Objects/challenge-06.js:
--------------------------------------------------------------------------------
1 | // You just need to implement the mergeObjects function
2 | function mergeObjects(obj1, obj2) {
3 | // Merge obj1 and obj2 into a single object
4 | if (typeof obj1 === 'object' && typeof obj2 === 'object') {
5 | if (obj1 != {} || obj2 != {}) {
6 | return Object.assign(obj1, obj2);
7 | }
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/016-CodeChallenges/006-Objects/challenge-07.js:
--------------------------------------------------------------------------------
1 | // You just need to implement the objectToArray function
2 | function objectToArray(obj) {
3 | // Convert the object into an array of key-value pairs
4 | if (typeof obj == "object") {
5 | return Object.entries(obj);
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/016-CodeChallenges/006-Objects/challenge-08.js:
--------------------------------------------------------------------------------
1 | // You just need to implement the cleanObject function
2 | function cleanObject(obj) {
3 | // Remove all properties with null or undefined values
4 | if (typeof obj === "object" && obj !== null) {
5 | for (let property in obj) {
6 | if (obj[property] === null || typeof obj[property] === "undefined") {
7 | delete obj[property];
8 | }
9 | }
10 |
11 | if (Object.keys(obj) == []) {
12 | return {};
13 | }
14 | }
15 |
16 | return obj;
17 | }
18 |
--------------------------------------------------------------------------------
/016-CodeChallenges/006-Objects/challenge-09.js:
--------------------------------------------------------------------------------
1 | // You just need to implement the deepClone function
2 | function deepClone(obj) {
3 | // Return a deep copy of obj
4 |
5 | if (typeof obj === "object" && obj !== null) {
6 | const objString = JSON.stringify(obj);
7 | const newObj = JSON.parse(objString);
8 | return newObj;
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/016-CodeChallenges/006-Objects/challenge-10.js:
--------------------------------------------------------------------------------
1 | // You just need to implement the getNestedValue function
2 | function getNestedValue(obj, keyPath) {
3 | // Return the value from the nested object based on keyPath
4 | const pathArray = keyPath.split(".");
5 |
6 | for (let i = 0; i < pathArray.length; i++) {
7 | if (obj === null || obj[pathArray[i]] === undefined) {
8 | return "Key not found";
9 | }
10 | obj = obj[pathArray[i]];
11 | }
12 |
13 | return obj;
14 | }
15 |
--------------------------------------------------------------------------------
/017-Practice/001-JS-Basics/README.md:
--------------------------------------------------------------------------------
1 | # JS Basics
2 |
3 | 1a
4 | 
5 |
6 | 1b
7 | 
8 |
9 | 1c 1d 1e
10 | 
11 |
12 | 1f
13 | 
14 |
15 | 1g
16 | 
17 |
18 | 1h 1i
19 | 
20 |
21 |
22 | 1j
23 | 
24 |
25 | ## Referece
26 |
27 | - [Exercise link](https://github.com/SuperSimpleDev/javascript-course/blob/main/1-exercise-solutions/lesson-01/README.md)
28 | - [Exercise credits](https://github.com/SuperSimpleDev)
29 |
--------------------------------------------------------------------------------
/017-Practice/001-JS-Basics/exercise-1a.js:
--------------------------------------------------------------------------------
1 | alert('Good Morning!');
--------------------------------------------------------------------------------
/017-Practice/001-JS-Basics/exercise-1b.js:
--------------------------------------------------------------------------------
1 | alert('Iron Man');
--------------------------------------------------------------------------------
/017-Practice/001-JS-Basics/exercise-1c.js:
--------------------------------------------------------------------------------
1 | 10 + 5
--------------------------------------------------------------------------------
/017-Practice/001-JS-Basics/exercise-1d.js:
--------------------------------------------------------------------------------
1 | 20 - 5
--------------------------------------------------------------------------------
/017-Practice/001-JS-Basics/exercise-1e.js:
--------------------------------------------------------------------------------
1 | 2 + 2 - 5
--------------------------------------------------------------------------------
/017-Practice/001-JS-Basics/exercise-1f.js:
--------------------------------------------------------------------------------
1 | document.body.innerHTML = 'Good Morning!'
--------------------------------------------------------------------------------
/017-Practice/001-JS-Basics/exercise-1g.js:
--------------------------------------------------------------------------------
1 | document.body.innerHTML = 'Vishal'
--------------------------------------------------------------------------------
/017-Practice/001-JS-Basics/exercise-1h.js:
--------------------------------------------------------------------------------
1 | 10 + 8 + 20
--------------------------------------------------------------------------------
/017-Practice/001-JS-Basics/exercise-1i.js:
--------------------------------------------------------------------------------
1 | 100 - 20 -50 + 200
--------------------------------------------------------------------------------
/017-Practice/001-JS-Basics/exercise-1j.js:
--------------------------------------------------------------------------------
1 | document.body.innerHTML='';
--------------------------------------------------------------------------------
/017-Practice/002-Numbers-Maths/README.md:
--------------------------------------------------------------------------------
1 | # Numbers and Math
2 |
3 | 2a, 2b, 2c, 2d, 2e
4 | 
5 |
6 | 2f, 2g, 2h, 2i, 2j, 2k
7 | 
8 |
9 | 2l, 2m, 2n
10 | 
11 |
12 | ## Referece
13 |
14 | - [Exercise link](https://github.com/SuperSimpleDev/javascript-course/blob/main/1-exercise-solutions/lesson-02/README.md)
15 | - [Exercise credits](https://github.com/SuperSimpleDev)
16 |
--------------------------------------------------------------------------------
/017-Practice/002-Numbers-Maths/exercise-2a.js:
--------------------------------------------------------------------------------
1 | (1*10) + (3*8) + (1*5)
--------------------------------------------------------------------------------
/017-Practice/002-Numbers-Maths/exercise-2b.js:
--------------------------------------------------------------------------------
1 | ((1*10) + (3*8) + (1*5)) / 3
--------------------------------------------------------------------------------
/017-Practice/002-Numbers-Maths/exercise-2c.js:
--------------------------------------------------------------------------------
1 | 18.50 + (2 * 7.50)
--------------------------------------------------------------------------------
/017-Practice/002-Numbers-Maths/exercise-2d.js:
--------------------------------------------------------------------------------
1 | (18.50 + (2 * 7.50)) * 0.1
--------------------------------------------------------------------------------
/017-Practice/002-Numbers-Maths/exercise-2e.js:
--------------------------------------------------------------------------------
1 | (18.50 + (2 * 7.50)) * 0.2
--------------------------------------------------------------------------------
/017-Practice/002-Numbers-Maths/exercise-2f.js:
--------------------------------------------------------------------------------
1 | (2095 + 1899 + 799)/100
--------------------------------------------------------------------------------
/017-Practice/002-Numbers-Maths/exercise-2g.js:
--------------------------------------------------------------------------------
1 | (2095 + 1899 + 799 + 499)/100
--------------------------------------------------------------------------------
/017-Practice/002-Numbers-Maths/exercise-2h.js:
--------------------------------------------------------------------------------
1 | Math.round((2095 + 1899 + 799 + 499) * 0.1) / 100
--------------------------------------------------------------------------------
/017-Practice/002-Numbers-Maths/exercise-2i.js:
--------------------------------------------------------------------------------
1 | Math.round((2095 + 1899 + 799 + 499) + ((2095 + 1899 + 799 + 499) * 0.1)) / 100
--------------------------------------------------------------------------------
/017-Practice/002-Numbers-Maths/exercise-2j.js:
--------------------------------------------------------------------------------
1 | Math.floor(2.8)
--------------------------------------------------------------------------------
/017-Practice/002-Numbers-Maths/exercise-2k.js:
--------------------------------------------------------------------------------
1 | Math.ceil(2.2)
--------------------------------------------------------------------------------
/017-Practice/002-Numbers-Maths/exercise-2l.js:
--------------------------------------------------------------------------------
1 | ( 25 * (9/5)) + 32
--------------------------------------------------------------------------------
/017-Practice/002-Numbers-Maths/exercise-2m.js:
--------------------------------------------------------------------------------
1 | (86 - 32) * (5/9)
--------------------------------------------------------------------------------
/017-Practice/002-Numbers-Maths/exercise-2n.js:
--------------------------------------------------------------------------------
1 | ( -5 * (9/5)) + 32
--------------------------------------------------------------------------------
/017-Practice/003-Strings/README.md:
--------------------------------------------------------------------------------
1 | # Strings
2 |
3 | 3a, 3b, 3c, 3d, 3e, 3f
4 | 
5 |
6 | 3g, 3h, 3i, 3j
7 | 
8 |
9 | 3k, 3l, 3m, 3n
10 | 
11 |
12 | ## Referece
13 |
14 | - [Exercise link](https://github.com/SuperSimpleDev/javascript-course/blob/main/1-exercise-solutions/lesson-03/README.md)
15 | - [Exercise credits](https://github.com/SuperSimpleDev)
16 |
--------------------------------------------------------------------------------
/017-Practice/003-Strings/exercise-3a.js:
--------------------------------------------------------------------------------
1 | 'My name is:'
--------------------------------------------------------------------------------
/017-Practice/003-Strings/exercise-3b.js:
--------------------------------------------------------------------------------
1 | 'Vishal'
--------------------------------------------------------------------------------
/017-Practice/003-Strings/exercise-3c.js:
--------------------------------------------------------------------------------
1 | 'My name is: ' + 'Vishal'
--------------------------------------------------------------------------------
/017-Practice/003-Strings/exercise-3d.js:
--------------------------------------------------------------------------------
1 | 'Total cost: $' + (5+3)
--------------------------------------------------------------------------------
/017-Practice/003-Strings/exercise-3e.js:
--------------------------------------------------------------------------------
1 | `Total cost: $${5 + 3}`
--------------------------------------------------------------------------------
/017-Practice/003-Strings/exercise-3f.js:
--------------------------------------------------------------------------------
1 | alert(`Total cost: $${5 + 3}`)
--------------------------------------------------------------------------------
/017-Practice/003-Strings/exercise-3g.js:
--------------------------------------------------------------------------------
1 | 'Total cost: $' + (599+295)/100
--------------------------------------------------------------------------------
/017-Practice/003-Strings/exercise-3h.js:
--------------------------------------------------------------------------------
1 | `Total cost: $${(599+295)/100}`
--------------------------------------------------------------------------------
/017-Practice/003-Strings/exercise-3i.js:
--------------------------------------------------------------------------------
1 | alert(`Total cost: $${(599+295)/100}`);
--------------------------------------------------------------------------------
/017-Practice/003-Strings/exercise-3j.js:
--------------------------------------------------------------------------------
1 | alert(`Total cost: $${(599+295)/100}
2 | Thank you, come again!`);
--------------------------------------------------------------------------------
/017-Practice/003-Strings/exercise-3k.js:
--------------------------------------------------------------------------------
1 | `Items (${2+2}): $${((2*2095) + (2*799))/100}`
--------------------------------------------------------------------------------
/017-Practice/003-Strings/exercise-3l.js:
--------------------------------------------------------------------------------
1 | `Shipping & handling: $${4.99 + 4.99}`
--------------------------------------------------------------------------------
/017-Practice/003-Strings/exercise-3m.js:
--------------------------------------------------------------------------------
1 | `Total before tax: $${((2*2095) + 499 + (2*799) + 499)/100}`
--------------------------------------------------------------------------------
/017-Practice/003-Strings/exercise-3n.js:
--------------------------------------------------------------------------------
1 | `Estimated Tax: $${Math.round(((2*2095) + 499 + (2*799) + 499) * 0.1)/100}`
--------------------------------------------------------------------------------
/017-Practice/004-console-log/README.md:
--------------------------------------------------------------------------------
1 | # Writing JS with HTML and CSS
2 | [exercise.webm](https://github.com/user-attachments/assets/e0853c44-0a6b-4549-9509-e1c39c92d8f2)
3 |
4 | ## Referece
5 |
6 | - [Exercise link](https://github.com/SuperSimpleDev/javascript-course/blob/main/1-exercise-solutions/lesson-04/README.md)
7 | - [Exercise credits](https://github.com/SuperSimpleDev)
8 |
--------------------------------------------------------------------------------
/017-Practice/004-console-log/exercise-4.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Document
7 |
8 |
9 |
10 |
11 | Add to cart
12 | Buy now
13 |
14 |
15 |
16 |
19 |
20 |
--------------------------------------------------------------------------------
/017-Practice/005-Variables/README.md:
--------------------------------------------------------------------------------
1 | # Variables
2 |
3 | 
4 |
5 | ## Referece
6 |
7 | - [Exercise link](https://github.com/SuperSimpleDev/javascript-course/blob/main/1-exercise-solutions/lesson-05/README.md)
8 | - [Exercise credits](https://github.com/SuperSimpleDev)
9 |
--------------------------------------------------------------------------------
/017-Practice/005-Variables/exercise.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Calculator
7 |
8 |
15 |
16 |
17 |
18 |
19 |
20 | 1
21 | 2
22 | 3
23 | +
24 |
25 |
26 |
27 | 4
28 | 5
29 | 6
30 | -
31 |
32 |
33 |
34 | 7
35 | 8
36 | 9
37 | *
38 |
39 |
40 |
41 | 0
42 | .
43 | =
44 | /
45 |
46 |
47 |
48 | Clear
49 |
50 |
51 |
52 |
53 |
56 |
57 |
--------------------------------------------------------------------------------
/017-Practice/006-Booleans-IfStatements/README.md:
--------------------------------------------------------------------------------
1 | # Booleans and If Statements
2 | 
3 |
4 |
5 | ## Referece
6 |
7 | - [Exercise link](https://github.com/SuperSimpleDev/javascript-course/blob/main/1-exercise-solutions/lesson-06/README.md)
8 | - [Exercise credits](https://github.com/SuperSimpleDev)
9 |
--------------------------------------------------------------------------------
/017-Practice/006-Booleans-IfStatements/rock-paper-scissors.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Rock Paper Scissors
7 |
8 |
9 | Rock Paper Scissors
10 | Rock
37 |
38 | Paper
64 |
65 | Scissors
91 |
92 |
--------------------------------------------------------------------------------
/017-Practice/007-Functions/calculator.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Calculator
7 |
8 |
15 |
16 |
17 |
18 |
19 |
22 |
23 |
24 | 1
25 | 2
26 | 3
27 | +
28 |
29 |
30 |
31 | 4
32 | 5
33 | 6
34 | -
35 |
36 |
37 |
38 | 7
39 | 8
40 | 9
41 | *
42 |
43 |
44 |
45 | 0
46 | .
47 | =
48 | /
49 |
50 |
51 |
52 | Clear
55 |
56 |
57 |
58 |
59 |
68 |
69 |
--------------------------------------------------------------------------------
/017-Practice/007-Functions/rock-paper-scissors.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Rock Paper Scissors
7 |
8 |
9 | Rock Paper Scissors
10 | Rock
28 |
29 | Paper
47 |
48 | Scissors
66 |
67 |
84 |
85 |
--------------------------------------------------------------------------------
/017-Practice/008-Objects/calculator.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Calculator
7 |
8 |
15 |
16 |
17 |
18 |
19 |
22 |
23 |
24 | 1
25 | 2
26 | 3
27 | +
28 |
29 |
30 |
31 | 4
32 | 5
33 | 6
34 | -
35 |
36 |
37 |
38 | 7
39 | 8
40 | 9
41 | *
42 |
43 |
44 |
45 | 0
46 | .
47 | =
50 | /
51 |
52 |
53 |
54 | Clear
57 |
58 |
59 |
60 |
61 |
81 |
82 |
--------------------------------------------------------------------------------
/017-Practice/008-Objects/rock-paper-scissors.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Rock Paper Scissors
7 |
8 |
9 | Rock Paper Scissors
10 | Rock
13 |
14 | Paper
17 |
18 | Scissors
21 |
22 | Reset Score
25 |
26 |
115 |
116 |
--------------------------------------------------------------------------------
/017-Practice/009-DOM/Exercises/exercise-9a.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Document
7 |
8 |
9 | 9a
13 |
14 |
--------------------------------------------------------------------------------
/017-Practice/009-DOM/Exercises/exercise-9b.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Document
7 |
8 |
9 | 9a
13 |
14 | 9b
17 |
18 |
--------------------------------------------------------------------------------
/017-Practice/009-DOM/Exercises/exercise-9c.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Document
7 |
8 |
9 | heads
12 | tails
15 |
16 |
17 |
27 |
28 |
--------------------------------------------------------------------------------
/017-Practice/009-DOM/Exercises/exercise-9d.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Document
7 |
8 |
9 |
10 |
11 | Submit
14 |
15 |
16 |
17 |
26 |
27 |
--------------------------------------------------------------------------------
/017-Practice/009-DOM/Exercises/exercise-9e.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Document
7 |
8 |
9 |
12 |
13 | Submit
16 |
17 |
18 |
19 |
34 |
35 |
--------------------------------------------------------------------------------
/017-Practice/009-DOM/Exercises/exercise-9g.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Amazon Shipping Calculator
7 |
8 |
9 | Amazon Shipping Calculator
10 | Orders under $40 = +$10 shipping
11 | Orders over $40 = FREE shipping
12 |
13 |
16 | Calculate
22 |
23 |
24 |
25 |
61 |
62 |
--------------------------------------------------------------------------------
/017-Practice/009-DOM/Exercises/exercise-9h.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Document
7 |
8 |
9 |
10 |
14 |
15 |
16 |
17 |
35 |
36 |
--------------------------------------------------------------------------------
/017-Practice/009-DOM/Projects/amazon-shipping-calc.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Amazon Shipping Calculator
7 |
8 |
9 | Amazon Shipping Calculator
10 | Orders under $40 = +$10 shipping
11 | Orders over $40 = FREE shipping
12 |
13 |
16 | Calculate
22 |
23 |
24 |
25 |
61 |
62 |
--------------------------------------------------------------------------------
/017-Practice/009-DOM/Projects/calculator.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Calculator
7 |
8 |
15 |
16 |
17 |
18 |
19 | A
20 |
21 |
22 | 1
23 | 2
24 | 3
25 | +
26 |
27 |
28 |
29 | 4
30 | 5
31 | 6
32 | -
33 |
34 |
35 |
36 | 7
37 | 8
38 | 9
39 | *
40 |
41 |
42 |
43 | 0
44 | .
45 | =
48 | /
49 |
50 |
51 |
52 | Clear
55 |
56 |
57 |
58 |
59 |
93 |
94 |
--------------------------------------------------------------------------------
/017-Practice/009-DOM/Projects/youtube-subscribe.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Youtube Subscribe Button
7 |
8 |
9 |
10 | Youtube Subscribe Button
11 | Subscribe
14 |
15 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/017-Practice/009-DOM/dom.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | DOM
7 |
8 |
9 |
10 | Hello
11 |
12 |
34 |
35 |
--------------------------------------------------------------------------------
/017-Practice/010-DOMWithCSS/001-SubscribeButton/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Document
7 |
8 |
9 |
10 |
11 | Subscribe
14 |
15 |
16 |
--------------------------------------------------------------------------------
/017-Practice/010-DOMWithCSS/001-SubscribeButton/script.js:
--------------------------------------------------------------------------------
1 | function subscribe(){
2 |
3 | const subscribeButton = document.querySelector('.js-subscribe-btn');
4 |
5 | if(subscribeButton.classList.contains('is-subscribed')){
6 | subscribeButton.innerText = 'Subscribe';
7 | subscribeButton.classList.remove('is-subscribed');
8 | }else{
9 | subscribeButton.innerText = 'Subscribed';
10 | subscribeButton.classList.add('is-subscribed');
11 | }
12 | }
--------------------------------------------------------------------------------
/017-Practice/010-DOMWithCSS/001-SubscribeButton/style.css:
--------------------------------------------------------------------------------
1 | body{
2 | font-family: 'Arial';
3 | }
4 |
5 | .subscribe-btn{
6 | background-color: black;
7 | color: white;
8 | border: none;
9 | padding: 10px 15px;
10 | font-weight: bold;
11 | border-radius: 50px;
12 | cursor: pointer;
13 | }
14 |
15 | .is-subscribed{
16 | background-color: rgb(240, 240, 240);
17 | color: black;
18 | }
--------------------------------------------------------------------------------
/017-Practice/010-DOMWithCSS/002-RockPaperScissors/README.md:
--------------------------------------------------------------------------------
1 | Check [here](https://rock-paper-scissors-beryl-zeta.vercel.app/)
2 |
--------------------------------------------------------------------------------
/017-Practice/010-DOMWithCSS/002-RockPaperScissors/images/paper-emoji.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vsh26/JavaScrpit/3186e585fe2b45e551defbdaacdb8531c23894d8/017-Practice/010-DOMWithCSS/002-RockPaperScissors/images/paper-emoji.png
--------------------------------------------------------------------------------
/017-Practice/010-DOMWithCSS/002-RockPaperScissors/images/rock-emoji.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vsh26/JavaScrpit/3186e585fe2b45e551defbdaacdb8531c23894d8/017-Practice/010-DOMWithCSS/002-RockPaperScissors/images/rock-emoji.png
--------------------------------------------------------------------------------
/017-Practice/010-DOMWithCSS/002-RockPaperScissors/images/scissors-emoji.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vsh26/JavaScrpit/3186e585fe2b45e551defbdaacdb8531c23894d8/017-Practice/010-DOMWithCSS/002-RockPaperScissors/images/scissors-emoji.png
--------------------------------------------------------------------------------
/017-Practice/010-DOMWithCSS/002-RockPaperScissors/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Rock Paper Scissors
7 |
8 |
9 |
10 |
11 |
12 |
13 |
Rock Paper Scissors
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
32 |
33 |
34 |
35 |
36 |
Reset Score
37 |
38 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/017-Practice/010-DOMWithCSS/002-RockPaperScissors/style.css:
--------------------------------------------------------------------------------
1 | *{
2 | margin: 0;
3 | padding: 0;
4 | box-sizing: border-box;
5 | font-family: Arial;
6 | }
7 |
8 | body{
9 | background-color: black;
10 | height: 100vh;
11 | display: flex;
12 | justify-content: center ;
13 | align-items: center;
14 | }
15 |
16 | p{
17 | color: white;
18 | }
19 |
20 | button{
21 | cursor: pointer;
22 | }
23 |
24 | .container{
25 | min-width: 600px;
26 | padding: 10px;
27 | background-color: rgb(67, 67, 67);
28 | border-radius: 10px;
29 | text-align: center;
30 | }
31 |
32 | .title{
33 | font-size: 30px;
34 | font-weight: bold;
35 | padding: 10px 20px;
36 | margin-bottom: 10px;
37 | }
38 |
39 | .move-btn{
40 | height: 100px;
41 | width: 100px;
42 | border-radius: 50%;
43 | background-color: black;
44 | border: 2px solid white;
45 | margin: 10px;
46 | }
47 |
48 | .move-img{
49 | height: 50px;
50 | width: 50px;
51 | }
52 |
53 | .display-moves{
54 | font-size: 20px;
55 | padding: 10px;
56 | }
57 |
58 | .display-result{
59 | font-size: 20px;
60 | padding: 10px;
61 | }
62 |
63 | .display-score{
64 | font-size: 20px;
65 | padding: 10px;
66 | }
67 |
68 | .reset-btn{
69 | background-color: white;
70 | color: black;
71 | font-weight: bold;
72 | font-size: 16px;
73 | border: none;
74 | padding: 6px 8px;
75 | margin: 10px;
76 | border-radius: 20px;
77 | }
--------------------------------------------------------------------------------
/017-Practice/010-DOMWithCSS/003-Calculator/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Calculator
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 | 1
18 | 2
19 | 3
20 | +
21 |
22 |
23 |
24 | 4
25 | 5
26 | 6
27 | -
28 |
29 |
30 |
31 | 7
32 | 8
33 | 9
34 | *
35 |
36 |
37 |
38 | 0
39 | .
40 | =
43 | /
44 |
45 |
46 |
47 | C
50 |
51 |
52 |
53 |
54 |
55 |
--------------------------------------------------------------------------------
/017-Practice/010-DOMWithCSS/003-Calculator/script.js:
--------------------------------------------------------------------------------
1 | let calculation = localStorage.getItem("calculation") || "";
2 | updateDisplay();
3 |
4 | function updateCalculation(value) {
5 | calculation += value;
6 | console.log(calculation);
7 | updateDisplay();
8 | saveCalculation();
9 | }
10 |
11 | function total() {
12 | calculation = eval(calculation);
13 | console.log(calculation);
14 | updateDisplay();
15 | saveCalculation();
16 | }
17 |
18 | function clearCalculation() {
19 | calculation = "";
20 | updateDisplay();
21 | localStorage.removeItem("calculation");
22 | }
23 |
24 | function saveCalculation() {
25 | localStorage.setItem("calculation", calculation);
26 | }
27 |
28 | function updateDisplay() {
29 | document.querySelector(".display-area").innerText = calculation || "0";
30 | }
31 |
--------------------------------------------------------------------------------
/017-Practice/010-DOMWithCSS/003-Calculator/style.css:
--------------------------------------------------------------------------------
1 | *{
2 | margin: 0;
3 | padding: 0;
4 | box-sizing: border-box;
5 | font-family: Arial;
6 | }
7 |
8 | body{
9 | height: 100vh;
10 | display: flex;
11 | justify-content: center;
12 | align-items: center;
13 |
14 | }
15 |
16 | .calc-container{
17 | padding: 10px;
18 | border: 1px solid black;
19 | background-color: black;
20 | }
21 |
22 | .display-area{
23 | border: 1px solid black;
24 | padding: 10px;
25 | margin: 10px;
26 | font-size: 20px;
27 | background-color: white;
28 | color: black;
29 | }
30 |
31 | button{
32 | height: 50px;
33 | width: 50px;
34 | border: none;
35 | background-color: rgb(90, 90, 90);
36 | color: white;
37 | font-size: 20px;
38 | font-weight: bold;
39 | border-radius: 50%;
40 | margin: 4px;
41 | }
42 |
43 | .operations{
44 | background-color: rgb(137, 137, 137);
45 | color: rgb(77, 255, 86);
46 | }
--------------------------------------------------------------------------------
/017-Practice/011-ArraysAndLoops/Exercises/exercise.js:
--------------------------------------------------------------------------------
1 | // 11a
2 | const nums = [10, 20, 30];
3 | nums[nums.length-1] = 99;
4 | console.log(nums);
5 |
6 | // 11b
7 | function getLastValue(arr){
8 | return arr[arr.length - 1];
9 | }
10 | console.log(getLastValue(nums));
11 |
12 | // 11c
13 | function arraySwap(arr){
14 | const temp = arr[arr.length - 1];
15 | arr[arr.length - 1] = arr[0];
16 | arr[0] = temp;
17 |
18 | return arr;
19 | }
20 |
21 | console.log(arraySwap(nums));
22 |
23 | // 11d
24 | for(let i = 0; i <= 10; i += 2){
25 | console.log(i);
26 | }
27 |
28 | // 11e
29 | for(let i = 5; i >= 0; i--){
30 | console.log(i);
31 | }
32 |
33 | // 11f
34 | let i = 0;
35 |
36 | while(i <= 10){
37 | console.log(i);
38 | i += 2;
39 | }
40 |
41 | let j = 5;
42 |
43 | while(j >= 0){
44 | console.log(j);
45 | j--;
46 | }
47 |
48 | // 1g
49 | const nums1 = [1, 2, 3];
50 | const nums2 = [];
51 | for(let i = 0; i < nums1.length; i++){
52 | nums2.push(nums1[i] + 1);
53 | }
54 |
55 | console.log(nums2);
56 |
57 | // 11h
58 | function addOne(arr){
59 | for(let i = 0; i < arr.length; i++){
60 | arr[i] += 1;
61 | }
62 | return arr;
63 | }
64 |
65 | console.log(addOne([1, 2, 3]));
66 | console.log(addOne([-2, -1, 0, 99]));
67 |
68 | // 11i
69 | function addNum(arr, num){
70 | for(let i = 0; i < arr.length; i++){
71 | arr[i] += num;
72 | }
73 | return arr;
74 | }
75 |
76 | console.log(addNum([1, 2, 3], 2));
77 | console.log(addNum([1, 2, 3], 3));
78 | console.log(addNum([-2, -1, 0, 99], 2));
79 |
80 | // 11j
81 | function addArrays(arr1, arr2){
82 | if(arr1.length === arr2.length){
83 | for(let i = 0; i < arr1.length; i++){
84 | arr1[i] += arr2[i];
85 | }
86 | return arr1;
87 | }
88 | return;
89 | }
90 | console.log(addArrays([1, 1, 2], [1, 1, 3]));
91 | console.log(addArrays([1, 2, 3], [4, 5, 6]));
92 |
93 | // 11k
94 | function countPositive(arr){
95 | let positiveCount = 0;
96 | for(let i = 0; i < arr.length; i++){
97 | if(arr[i] > 0){
98 | positiveCount++;
99 | }
100 | }
101 | return positiveCount;
102 | }
103 |
104 | console.log(countPositive([1, -3, 5]));
105 | console.log(countPositive([-2, 3, -5, 7, 10]));
106 |
107 | // 11l, 11m
108 | function minMax(arr){
109 |
110 | if(arr.length === 0){
111 | return {min: null, max: null};
112 | }
113 |
114 | let arrMin = arr[0];
115 | let arrMax = arr[0];
116 |
117 | for(let i = 1; i < arr.length; i++){
118 | if(arr[i] < arrMin){
119 | arrMin = arr[i];
120 | }
121 |
122 | if(arr[i] > arrMax){
123 | arrMax = arr[i];
124 | }
125 | }
126 |
127 | return {min: arrMin, max: arrMax};
128 | }
129 |
130 | console.log(minMax([1, -3, 5]));
131 | console.log(minMax([-2, 3, -5, 7, 10]));
132 | console.log(minMax([]));
133 | console.log(minMax([3]));
134 |
135 | // 11n
136 | function countWords(arr){
137 | const obj = {};
138 |
139 | for(i = 0; i < arr.length; i++){
140 | if(obj[arr[i]]){
141 | obj[arr[i]] += 1;
142 | }else{
143 | obj[arr[i]] = 1;
144 | }
145 | }
146 |
147 | return obj;
148 | }
149 |
150 | console.log(countWords(['apple', 'grape', 'apple', 'apple']));
151 |
--------------------------------------------------------------------------------
/017-Practice/011-ArraysAndLoops/TodoList/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Todo List
7 |
8 |
9 |
10 |
11 |
12 |
Todo List
13 |
14 |
15 |
16 | Add
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/017-Practice/011-ArraysAndLoops/TodoList/script.js:
--------------------------------------------------------------------------------
1 | const addButton = document.querySelector(".js-add-btn");
2 | const deleteButton = document.querySelector(".js-delete-btn");
3 | const displayTasks = document.querySelector(".js-display-tasks");
4 | const todoList = [];
5 |
6 | // const todoList = [{
7 | // todoName: 'task1',
8 | // dueDate: '2025-03-22'
9 | // }, {
10 | // todoName: 'task2',
11 | // dueDate: '2025-02-22'
12 | // }];
13 |
14 | function renderSavedTodoList(){
15 | const savedTodo = JSON.parse(localStorage.getItem('savedTodo')) || [];
16 | todoList.push(...savedTodo);
17 | renderTodoList();
18 | }
19 |
20 | function renderTodoList(){
21 | let todoListHTML = '';
22 |
23 | for(let i = 0; i ${todoList[i].todoName}
27 | ${todoList[i].dueDate}
28 | Delete
36 | `;
37 | todoListHTML += displayTasksHTML;
38 |
39 | // console.log(todoList[i]);
40 |
41 | }
42 |
43 | displayTasks.innerHTML = todoListHTML;
44 | }
45 |
46 | function addTask(){
47 |
48 | const inputText = document.querySelector(".js-input-text");
49 | const task = inputText.value;
50 |
51 | const inputDueDate = document.querySelector(".js-input-due-date");
52 | const dueDateValue = inputDueDate.value;
53 |
54 | if(task === '' || dueDateValue === ''){
55 | return;
56 | }
57 |
58 | todoList.push({todoName:task, dueDate:dueDateValue});
59 | // console.log(todoList);
60 | localStorage.setItem('savedTodo', JSON.stringify(todoList));
61 | renderTodoList();
62 |
63 | inputText.value = '';
64 | inputDueDate.value = '';
65 |
66 | }
67 |
68 | addButton.addEventListener('click', addTask);
69 | renderSavedTodoList();
--------------------------------------------------------------------------------
/017-Practice/011-ArraysAndLoops/TodoList/style.css:
--------------------------------------------------------------------------------
1 | *{
2 | margin: 0;
3 | padding: 0;
4 | box-sizing: border-box;
5 | font-family: Arial;
6 | }
7 |
8 | body{
9 | height: 100vh;
10 | display: flex;
11 | justify-content: center;
12 | align-items: center;
13 | }
14 |
15 | #todo-title{
16 | font-size: 1.6rem;
17 | padding: 6px;
18 | margin-bottom: 10px;
19 | }
20 |
21 | .input-text,
22 | .date-picker{
23 | font-size: 15px;
24 | padding: 6px;
25 | }
26 |
27 | .add-btn, .delete-btn{
28 | font-size: 15px;
29 | padding: 10px 20px;
30 | color: white;
31 | border: none;
32 | cursor: pointer;
33 | }
34 |
35 | .add-btn{
36 | background-color: green;
37 | }
38 |
39 | .delete-btn{
40 | background-color: rgb(170, 22, 22);
41 | }
42 |
43 | .todo-input-grid,
44 | .todo-grid{
45 | display: grid;
46 | grid-template-columns: 300px 150px 100px;
47 | column-gap: 10px;
48 | row-gap: 10px;
49 | align-items: center;
50 | }
51 |
52 | .todo-input-grid{
53 | margin-bottom: 10px;
54 | }
--------------------------------------------------------------------------------
/017-Practice/012-AdvancedFunctions/12a.js:
--------------------------------------------------------------------------------
1 | const add = function(){
2 | console.log(2+3);
3 | }
4 |
5 | add();
6 | add();
--------------------------------------------------------------------------------
/017-Practice/012-AdvancedFunctions/12b.js:
--------------------------------------------------------------------------------
1 | const add = function(){
2 | console.log(2+3);
3 | }
4 |
5 | const newFn = function(){
6 | console.log('12b');
7 | }
8 |
9 | function runTwice(fun){
10 | fun();
11 | fun();
12 | }
13 |
14 | runTwice(add);
15 | runTwice(newFn);
--------------------------------------------------------------------------------
/017-Practice/012-AdvancedFunctions/12c.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Document
7 |
8 |
9 | Finish
10 |
11 |
12 |
--------------------------------------------------------------------------------
/017-Practice/012-AdvancedFunctions/12c.js:
--------------------------------------------------------------------------------
1 | const finishButton = document.querySelector('#finish-btn');
2 |
3 | function finishedFn(){
4 | setTimeout(()=>{
5 | finishButton.innerText = 'Finished!'
6 | }, 1000);
7 | }
8 |
9 | finishButton.addEventListener('click', finishedFn);
--------------------------------------------------------------------------------
/017-Practice/012-AdvancedFunctions/12d.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Document
7 |
8 |
9 | Finish
10 |
11 |
12 |
--------------------------------------------------------------------------------
/017-Practice/012-AdvancedFunctions/12d.js:
--------------------------------------------------------------------------------
1 | const finishButton = document.querySelector('#finish-btn');
2 |
3 | function finishedFn(){
4 | setTimeout(()=>{
5 | finishButton.innerText = 'Finished!';
6 | }, 1000);
7 | }
8 |
9 | finishButton.addEventListener('click', () => {
10 | finishedFn();
11 | finishButton.innerText = 'Loading...';
12 | });
--------------------------------------------------------------------------------
/017-Practice/012-AdvancedFunctions/12e.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Document
7 |
8 |
9 | Add to Cart
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/017-Practice/012-AdvancedFunctions/12e.js:
--------------------------------------------------------------------------------
1 | const addToCartButton = document.querySelector('#add-btn');
2 | const displayText = document.querySelector('#display-text');
3 |
4 | function clearText(){
5 | setTimeout(()=>{
6 | displayText.innerText = '';
7 | }, 2000);
8 | }
9 |
10 | addToCartButton.addEventListener('click', () => {
11 | displayText.innerText = 'Added';
12 | clearText();
13 | });
--------------------------------------------------------------------------------
/017-Practice/012-AdvancedFunctions/12f.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Document
7 |
8 |
9 | Add to Cart
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/017-Practice/012-AdvancedFunctions/12f.js:
--------------------------------------------------------------------------------
1 | const addToCartButton = document.querySelector('#add-btn');
2 | const displayText = document.querySelector('#display-text');
3 |
4 | let timeoutID;
5 | function clearText(){
6 |
7 | clearTimeout(timeoutID);
8 |
9 | timeoutID = setTimeout(()=>{
10 | displayText.innerText = '';
11 | }, 2000);
12 | }
13 |
14 | addToCartButton.addEventListener('click', () => {
15 | displayText.innerText = 'Added';
16 | clearText();
17 | });
--------------------------------------------------------------------------------
/017-Practice/012-AdvancedFunctions/12g.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Document
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/017-Practice/012-AdvancedFunctions/12g.js:
--------------------------------------------------------------------------------
1 | function updateTitle(){
2 | if(document.title === 'Document'){
3 | document.title = '(2) New Messages';
4 | } else {
5 | document.title = 'Document';
6 | }
7 | }
8 |
9 | setInterval(updateTitle, 1000);
--------------------------------------------------------------------------------
/017-Practice/012-AdvancedFunctions/12h.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Document
7 |
8 |
9 | Add
10 | Remove
11 |
12 |
13 |
--------------------------------------------------------------------------------
/017-Practice/012-AdvancedFunctions/12h.js:
--------------------------------------------------------------------------------
1 | const addButton = document.querySelector('#add-btn');
2 | const removeButton = document.querySelector('#remove-btn');
3 |
4 | let messageNum = 0;
5 |
6 | function updateTitle(){
7 |
8 | if(document.title === 'Document'){
9 | document.title = `(${messageNum}) New Message`
10 | } else {
11 | document.title = 'Document';
12 | }
13 |
14 | }
15 |
16 | setInterval(updateTitle, 1000);
17 |
18 | function increaseNum(){
19 | messageNum++;
20 | }
21 |
22 | function decreaseNum(){
23 | messageNum--;
24 | }
25 |
26 | addButton.addEventListener('click', increaseNum);
27 | removeButton.addEventListener('click', decreaseNum);
--------------------------------------------------------------------------------
/017-Practice/012-AdvancedFunctions/12i.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Document
7 |
8 |
9 | Add
10 | Remove
11 |
12 |
13 |
--------------------------------------------------------------------------------
/017-Practice/012-AdvancedFunctions/12i.js:
--------------------------------------------------------------------------------
1 | const addButton = document.querySelector('#add-btn');
2 | const removeButton = document.querySelector('#remove-btn');
3 |
4 | let messageNum = 0;
5 |
6 | function updateTitle(){
7 |
8 | if((document.title === 'Document') && (messageNum > 0)){
9 | document.title = `(${messageNum}) New Message`
10 | } else {
11 | document.title = 'Document';
12 | }
13 |
14 | }
15 |
16 | setInterval(updateTitle, 1000);
17 |
18 | function increaseNum(){
19 | messageNum++;
20 | }
21 |
22 | function decreaseNum(){
23 | messageNum--;
24 | if(messageNum < 0){
25 | messageNum = 0;
26 | }
27 | }
28 |
29 | addButton.addEventListener('click', increaseNum);
30 | removeButton.addEventListener('click', decreaseNum);
--------------------------------------------------------------------------------
/017-Practice/012-AdvancedFunctions/12j.js:
--------------------------------------------------------------------------------
1 | const multiply = (num1, num2) => {
2 | return num1 * num2;
3 | }
4 |
5 | console.log(multiply(2, 3));
6 | console.log(multiply(2, 4));
--------------------------------------------------------------------------------
/017-Practice/012-AdvancedFunctions/12k.js:
--------------------------------------------------------------------------------
1 | const multiply = (num1, num2) => num1 * num2;
2 |
3 | console.log(multiply(2, 3));
4 | console.log(multiply(2, 4));
--------------------------------------------------------------------------------
/017-Practice/012-AdvancedFunctions/12l.js:
--------------------------------------------------------------------------------
1 | function countPositive(arr){
2 | let count = 0;
3 | arr.forEach(element => {
4 | if(element > 0){
5 | count++;
6 | }
7 | });
8 |
9 | return count;
10 | }
11 |
12 | console.log(countPositive([1, -3, 5]));
13 | console.log(countPositive([-2, 3, -5, 7, 10]));
--------------------------------------------------------------------------------
/017-Practice/012-AdvancedFunctions/12m.js:
--------------------------------------------------------------------------------
1 | // function addNum(arr, num){
2 | // return arr.map(element => element + num);
3 | // }
4 |
5 | const addNum = (arr, num) => arr.map(element => element + num);
6 |
7 | console.log(addNum([1, 2, 3], 2));
8 | console.log(addNum([-2, -1, 0, 99], 2));
--------------------------------------------------------------------------------
/017-Practice/012-AdvancedFunctions/12n.js:
--------------------------------------------------------------------------------
1 | function removeEggs(foods){
2 | const result = foods.filter((food) => food !== 'egg');
3 | return result;
4 | }
5 |
6 | console.log(removeEggs(['egg', 'apple', 'egg', 'egg', 'ham']));
--------------------------------------------------------------------------------
/017-Practice/012-AdvancedFunctions/12o.js:
--------------------------------------------------------------------------------
1 | function removeEggs(foods){
2 | let eggCount = 0;
3 |
4 | const result = foods.filter((food) => {
5 |
6 | if(food === 'egg' && eggCount < 2){
7 | eggCount++;
8 | return false;
9 | }
10 | return true;
11 | });
12 |
13 | return result;
14 | }
15 |
16 | console.log(removeEggs(['egg', 'apple', 'egg', 'egg', 'ham']));
--------------------------------------------------------------------------------
/017-Practice/012-AdvancedFunctions/README.md:
--------------------------------------------------------------------------------
1 | # Advanced Functions
2 | ## Referece
3 |
4 | - [Exercise link](https://github.com/SuperSimpleDev/javascript-course/blob/main/1-exercise-solutions/lesson-12/README.md)
5 | - [Exercise credits](https://github.com/SuperSimpleDev)
6 |
--------------------------------------------------------------------------------
/018-Projects/001-Clock/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Clock
7 |
8 |
9 |
10 |
11 |
12 |
HH:MM:SS AM
13 |
Loading date ...
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/018-Projects/001-Clock/script.js:
--------------------------------------------------------------------------------
1 | function updateClock(){
2 |
3 | const timeElement = document.querySelector("#time-container");
4 | const dateElement = document.querySelector("#date-container");
5 |
6 | const now = new Date();
7 |
8 | const hours = (now.getHours() % 12 || 12);
9 | const minutes = now.getMinutes().toString().padStart(2, "0");
10 | const seconds = now.getSeconds().toString().padStart(2, "0");
11 |
12 | const ampm = (now.getHours() >= 12 ? "PM" : "AM");
13 |
14 | timeElement.innerText = `${hours}:${minutes}:${seconds} ${ampm}`;
15 |
16 | const options = {
17 | weekday: "long",
18 | year: "numeric",
19 | month: "long",
20 | day: "numeric"
21 | };
22 |
23 | dateElement.innerText = now.toLocaleDateString(undefined, options);
24 | }
25 |
26 | setInterval(updateClock, 1000);
27 | updateClock();
--------------------------------------------------------------------------------
/018-Projects/001-Clock/style.css:
--------------------------------------------------------------------------------
1 | * {
2 | margin: 0;
3 | padding: 0;
4 | box-sizing: border-box;
5 | font-family: Arial;
6 | }
7 |
8 |
9 | body{
10 | background-color: rgb(78, 74, 74);
11 | height: 100vh;
12 | display: flex;
13 | justify-content: center ;
14 | align-items: center;
15 | }
16 |
17 | .clock-container{
18 | text-align: center;
19 | background-color: rgb(246, 234, 218);
20 | padding: 50px ;
21 | border-radius: 20px;
22 | box-shadow: 0 8px 30px rgb(25, 25, 25);
23 | }
24 |
25 | #time-container{
26 | font-size: 5rem;
27 | color:rgb(0, 0, 0);
28 | margin-bottom: 10px;
29 | letter-spacing: 3px;
30 | }
31 |
32 | #date-container{
33 | font-size: 1.6rem;
34 | color:rgb(0, 0, 0)
35 | }
--------------------------------------------------------------------------------
/018-Projects/002-CountdownTimer/README.md:
--------------------------------------------------------------------------------
1 | Check [here](https://countdown-timer-ochre-two.vercel.app/)
2 |
--------------------------------------------------------------------------------
/018-Projects/002-CountdownTimer/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Countdown Timer
7 |
8 |
9 |
10 |
11 |
12 |
13 |
Countdown Timer
14 |
15 |
Start Countdown
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/018-Projects/002-CountdownTimer/script.js:
--------------------------------------------------------------------------------
1 | const startButton = document.querySelector('#start-button');
2 | const timeInput = document.querySelector('#input-box');
3 | const countdownDisplay = document.querySelector('#countdown-display')
4 |
5 | function startTimer(){
6 |
7 | let timeInputValue = parseInt(timeInput.value);
8 |
9 | console.log(timeInputValue);
10 | // console.log(typeof timeInputValue);
11 |
12 | if(isNaN(timeInputValue)){
13 | countdownDisplay.innerText = 'Please enter a valid number';
14 | return;
15 | }
16 |
17 | if(timeInputValue <= 0){
18 | countdownDisplay.innerText = 'Please enter seconds > 0';
19 | return;
20 | }
21 |
22 | const timer = setInterval(() => {
23 | timeInputValue--;
24 | countdownDisplay.innerText = `Time remaining: ${timeInputValue}`;
25 |
26 | if(timeInputValue === 0){
27 | clearInterval(timer);
28 | countdownDisplay.innerText = 'Time up!';
29 | }
30 | }, 1000);
31 | }
32 |
33 | startButton.addEventListener('click', startTimer);
--------------------------------------------------------------------------------
/018-Projects/003-RandomQuoteGenerator/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Random Quote Generator
7 |
8 |
9 |
10 |
11 |
12 |
Random Quote Generator
13 |
Click the button to get a quote!
14 |
Generate Button
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/018-Projects/003-RandomQuoteGenerator/script.js:
--------------------------------------------------------------------------------
1 | const quotes = [
2 | "Do what you can, with what you have, where you are. — Theodore Roosevelt",
3 | "Opportunities don\'t happen. You create them. — Chris Grosser",
4 | "Simplicity is the ultimate sophistication. — Leonardo da Vinci",
5 | "The best way to predict the future is to create it. — Peter Drucker",
6 | "Act as if what you do makes a difference. It does. — William James",
7 | "Success is not final, failure is not fatal: it is the courage to continue that counts. — Winston Churchill",
8 | "Dream big and dare to fail. — Norman Vaughan",
9 | "The only way to do great work is to love what you do. — Steve Jobs",
10 | "Your time is limited, so don\'t waste it living someone else\'s life. — Steve Jobs",
11 | "Courage is resistance to fear, mastery of fear, not absence of fear. — Mark Twain",
12 | "The only limit to our realization of tomorrow is our doubts of today. — Franklin D. Roosevelt",
13 | "Don't watch the clock; do what it does. Keep going. — Sam Levenson",
14 | "Happiness depends upon ourselves. — Aristotle",
15 | "Doubt kills more dreams than failure ever will. — Suzy Kassem",
16 | "Difficulties in life are intended to make us better, not bitter. — Dan Reeves",
17 | "It does not matter how slowly you go as long as you do not stop. — Confucius",
18 | "Everything you\'ve ever wanted is on the other side of fear. — George Addair",
19 | "Change your thoughts and you change your world. — Norman Vincent Peale",
20 | "Do not wait to strike till the iron is hot, but make it hot by striking. — William Butler Yeats",
21 | "The harder the conflict, the greater the triumph. — George Washington"
22 | ];
23 |
24 | const quoteDisplay = document.querySelector("#display-quote");
25 | const generateButton = document.querySelector("#generate-btn");
26 |
27 | function generateRandomQuote(){
28 |
29 | const randomNum = Math.floor(Math.random() * quotes.length);
30 | const quote = quotes[randomNum];
31 | quoteDisplay.innerText = quote;
32 |
33 | }
34 |
35 | generateButton.addEventListener('click', generateRandomQuote);
36 |
--------------------------------------------------------------------------------
/018-Projects/003-RandomQuoteGenerator/style.css:
--------------------------------------------------------------------------------
1 | *{
2 | margin: 0;
3 | padding: 0;
4 | box-sizing: border-box;
5 | font-family: Arial;
6 | }
7 |
8 | body{
9 | padding: 10px;
10 | display: flex;
11 | height: 100vh;
12 | justify-content: center;
13 | align-items: center;
14 | }
15 |
16 | .container{
17 | text-align: center;
18 | }
19 |
20 | #main-title{
21 | font-size: 2rem;
22 | padding: 10px;
23 | }
24 |
25 | #display-quote{
26 | max-width: 700px;
27 | font-size: 1.5rem;
28 | margin: 20px;
29 | }
30 |
31 | #generate-btn{
32 | padding: 10px 20px;
33 | font-size: 1rem;
34 | cursor: pointer;
35 | }
--------------------------------------------------------------------------------
/018-Projects/004-TodoList/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Todo List
7 |
8 |
9 |
10 |
11 |
12 |
Todo List
13 |
14 |
15 |
16 | Add
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/018-Projects/004-TodoList/script.js:
--------------------------------------------------------------------------------
1 | const addButton = document.querySelector(".js-add-btn");
2 | const deleteButton = document.querySelector(".js-delete-btn");
3 | const displayTasks = document.querySelector(".js-display-tasks");
4 | const todoList = [];
5 |
6 | // const todoList = [{
7 | // todoName: 'task1',
8 | // dueDate: '2025-03-22'
9 | // }, {
10 | // todoName: 'task2',
11 | // dueDate: '2025-02-22'
12 | // }];
13 |
14 | function renderSavedTodoList(){
15 | const savedTodo = JSON.parse(localStorage.getItem('savedTodo')) || [];
16 | todoList.push(...savedTodo);
17 | renderTodoList();
18 | }
19 |
20 | function renderTodoList(){
21 | let todoListHTML = '';
22 |
23 | for(let i = 0; i ${todoList[i].todoName}
27 | ${todoList[i].dueDate}
28 | Delete
36 | `;
37 | todoListHTML += displayTasksHTML;
38 |
39 | // console.log(todoList[i]);
40 |
41 | }
42 |
43 | displayTasks.innerHTML = todoListHTML;
44 | }
45 |
46 | function addTask(){
47 |
48 | const inputText = document.querySelector(".js-input-text");
49 | const task = inputText.value;
50 |
51 | const inputDueDate = document.querySelector(".js-input-due-date");
52 | const dueDateValue = inputDueDate.value;
53 |
54 | if(task === '' || dueDateValue === ''){
55 | return;
56 | }
57 |
58 | todoList.push({todoName:task, dueDate:dueDateValue});
59 | // console.log(todoList);
60 | localStorage.setItem('savedTodo', JSON.stringify(todoList));
61 | renderTodoList();
62 |
63 | inputText.value = '';
64 | inputDueDate.value = '';
65 |
66 | }
67 |
68 | addButton.addEventListener('click', addTask);
69 | renderSavedTodoList();
--------------------------------------------------------------------------------
/018-Projects/004-TodoList/style.css:
--------------------------------------------------------------------------------
1 | *{
2 | margin: 0;
3 | padding: 0;
4 | box-sizing: border-box;
5 | font-family: Arial;
6 | }
7 |
8 | body{
9 | height: 100vh;
10 | display: flex;
11 | justify-content: center;
12 | align-items: center;
13 | }
14 |
15 | #todo-title{
16 | font-size: 1.6rem;
17 | padding: 6px;
18 | margin-bottom: 10px;
19 | }
20 |
21 | .input-text,
22 | .date-picker{
23 | font-size: 15px;
24 | padding: 6px;
25 | }
26 |
27 | .add-btn, .delete-btn{
28 | font-size: 15px;
29 | padding: 10px 20px;
30 | color: white;
31 | border: none;
32 | cursor: pointer;
33 | }
34 |
35 | .add-btn{
36 | background-color: green;
37 | }
38 |
39 | .delete-btn{
40 | background-color: rgb(170, 22, 22);
41 | }
42 |
43 | .todo-input-grid,
44 | .todo-grid{
45 | display: grid;
46 | grid-template-columns: 300px 150px 100px;
47 | column-gap: 10px;
48 | row-gap: 10px;
49 | align-items: center;
50 | }
51 |
52 | .todo-input-grid{
53 | margin-bottom: 10px;
54 | }
--------------------------------------------------------------------------------
/Warmup/002Feb08th.js:
--------------------------------------------------------------------------------
1 | // Problem: Create an array containing diff. types of teas
2 | const teas = ["Greean tea", "Black tea", "Oolong tea", "White tea", "Herbal tea"];
3 | console.log(teas);
4 |
5 | // Problem: Add "Chamomile tea" to the existing list of teas
6 | teas.push("Chamomile tea");
7 | console.log(teas);
8 |
9 | // Problem: Remove "Oolong tea" from the list of teas
10 | const index = teas.indexOf("Oolong Tea");
11 | if(index > -1){
12 | teas.splice(index, 1);
13 | }
14 |
15 | console.log(teas);
16 |
17 | // Problem: Filter the list to only include teas that are caffinated
18 | const caffinatedTeas = teas.filter((tea) => tea != "Herbal tea");
19 | console.log(caffinatedTeas);
20 |
21 | // Problem: Sort the list of teas in alphabetical order
22 | console.log(teas.sort());
23 |
24 | // Problem: Use a for loop to print each type of tea in array
25 | for(let i = 0; i < teas.length; i++){
26 | console.log(teas[i]);
27 | }
28 |
29 | // Problem: Use a for loop to count how many teas are caffinated (excluding "Herbal tea")
30 | let caffinatedCount = 0;
31 | for(let i = 0; i < teas.length; i++){
32 | if(teas != "Herabl tea"){
33 | caffinatedCount++;
34 | }
35 | }
36 | console.log(caffinatedCount);
37 |
38 | // Problem: Use a for loop to create a new array with all tea names in uppercase
39 | const upperCaseTeas = [];
40 | for(let i = 0; i < teas.length; i++){
41 | upperCaseTeas.push(teas[i].toUpperCase());
42 | }
43 | console.log(upperCaseTeas);
44 |
45 | // Problem: Use a for loop to find tea name with the most characters
46 | let longestTea = "";
47 |
48 | for(let i = 0; i < teas.length; i++){
49 | if(teas[i].length > longestTea.length){
50 | longestTea = teas[i];
51 | }
52 | }
53 |
54 | console.log(longestTea);
55 |
56 | // Problem: Use a for loop to reverse the order of teas in the array
57 | const reversedArray = []
58 | for(let i = teas.length-1; i >=0; i--){
59 | reversedArray.push(teas[i]);
60 | }
61 |
62 | console.log(reversedArray);
--------------------------------------------------------------------------------
/Warmup/002Feb09th.js:
--------------------------------------------------------------------------------
1 | // Problem: Create an object representing a type of tea with properties for name, type and caffeine content
2 | const tea = {
3 | teaName : "Lemon Tea",
4 | teaType : "Green Tea",
5 | caffineContent : "Low"
6 | }
7 |
8 | // Problem: Accesss and print the name and type properties of the tea object
9 | console.log(tea.teaName);
10 | console.log(tea["teaType"]);
11 |
12 | // Problem: Add a new property origin to the tea object
13 | tea.origin = "Assam";
14 | console.log(tea);
15 |
16 | // Problem: Change the caffeine level of the tea object to 'medium'
17 | tea.caffineContent = "Medium";
18 | console.log(tea);
19 |
20 | // Problem: Remove the type property from the tea object
21 | delete tea.teaType;
22 | console.log(tea);
23 |
24 | // Problem: Check if tea object has a property origin
25 | console.log("origin" in tea);
26 |
27 | // Problem: Use for...in loop to print all properties of the tea object
28 | for (const key in tea) {
29 | console.log(`${key} : ${tea[key]}`);
30 | }
31 |
32 | // Problem: Create a nested object representing different types of teas and their properties
33 | const myTeas = {
34 | greenTea : {
35 | teaName : "Green Tea",
36 | cups : {
37 | one : "1",
38 | two : "2"
39 | }
40 | },
41 | blackTea : {
42 | teaName : "Black Tea"
43 | }
44 | }
45 |
46 | // Problem : Create a copy of tea object
47 |
48 | // Shallow Copy
49 | const teaCopy = {
50 | ...myTeas
51 | } // shallow copy (only first level keys are copied)
52 | console.log(teaCopy);
53 |
54 | // Reference
55 | const anotherCopy = myTeas; // Passing reference (anotherCopy is a reference)
56 |
57 | // Deep Copy
58 | const myTeasString = JSON.stringify(myTeas);
59 | const myTeasCopy = JSON.parse(myTeasString);
60 |
61 | console.log(myTeasCopy);
62 |
63 | // Problem : Add a custom method describe to the tea object that returns a description string
64 | // Problem : Merge two objects representing different teas into one
65 |
--------------------------------------------------------------------------------
/Warmup/002Feb12th.js:
--------------------------------------------------------------------------------
1 | Function.prototype.describe = function (){
2 | console.log(`Function name is ${this.name}`);
3 | }
4 |
5 | function greet(name){
6 | console.log(`Hello ${name}!`);
7 | }
8 |
9 | function userFunction(){
10 |
11 | }
12 |
13 | greet("Tony Stark"); // output: Hello Tony Stark!
14 | greet.describe(); // output: Function name is greet
15 | userFunction.describe(); // output: Function name is userFunction
16 |
17 | // This is function declaration
18 | function add(a, b){
19 | return a+b;
20 | }
21 |
22 | // This is function expression
23 | const subtract = function(a, b){
24 | return a-b;
25 | }
26 |
27 | // First class function
28 | function applyOperation(a, b, operation){
29 | return operation(a, b);
30 | }
31 |
32 | const result = applyOperation(5, 4, (x,y) => x/y);
33 | console.log(result);
34 |
35 |
36 | // Tiffin Concept
37 |
38 | function createCounter (){
39 | let count = 0;
40 |
41 | return function(){
42 | count++;
43 | return count;
44 | }
45 | }
46 |
47 | console.log(createCounter()); // Create counter is invoked and a function is returned
48 |
49 | const counter = createCounter(); // Create ounter is invoved, function is returned and stored in counter
50 | console.log(counter()); // The returned function is invoked and count is returned
51 |
52 |
53 | function onef(){
54 | let myName = "Tony";
55 | }
56 |
57 | // console.log(myName);
58 | // Scope of myName is only inside the function
59 |
60 | // function(){
61 | // console.log("Hello");
62 | // }()
63 |
64 | (function(){
65 | console.log("Hello");
66 | })()
--------------------------------------------------------------------------------