Lab guideFullStack

Full Stack Development Morning Jan 10 2022

Last updated 6 December 2023

Full Stack Development Morning Jan 10 2022

Scratchpad #1

let num = 10;

let x = 5;

15;

let result = 20;

undefined;

Scratchpad #2

// let highScoreOfPlayerOne = 10;
// let player1Score = 10;
// let GST_RATE = 18;

// let $highScore = 10;
// let _highScore = 10;
// let high_score = 10;

// let if = 10

// let num1 = 1;
// let num2 = '1';

// let result = num1 + num2;

// console.log(result);

let greeting = 'Hello World, Welcome to RST Forum.';

console.log(greeting.toUpperCase());
console.log(greeting.toLowerCase());

// Ctrl + `
// ls

Scratchpad #3

// let firstName = 'John';
// let lastName = 'Doe';
// let age = 20;

// // let message =
// //   "User's full name is " +
// //   firstName +
// //   ' ' +
// //   lastName +
// //   ' age his age is ' +
// //   age +
// //   '.';

// let message = `User's full name is ${firstName.toUpperCase()} ${lastName} and his age is ${
//   age * 100
// }`;

// console.log(message);

// let age = 21;

// if (age > 18) {
//   console.log('You can enter');
// }

// let num = 29;

// if (num % 2 === 0) {
//   console.log('Number is even');
// } else {
//   console.log('Number is odd');
// }

// let age = 'doh';

// if (age >= 65) {
//   console.log('Drinks are free');
// } else if (age >= 21) {
//   console.log('You can enter and drink');
// } else if (age >= 18) {
//   console.log("You can enter and but can't drink");
// } else {
//   console.log('You are not allowed');
// }

// if (typeof age === 'number') {
//   if (age >= 65) {
//     console.log('Drinks are free');
//   } else if (age >= 21) {
//     console.log('You can enter and drink');
//   } else if (age >= 18) {
//     console.log("You can enter and but can't drink");
//   } else {
//     console.log('You are not allowed');
//   }
// } else {
//   console.log('Please enter a valid age');
// }

// let password = 'hello world@123';

// if (password.length > 8) {
//   if (password.indexOf(' ') !== -1) {
//     console.log('Invalid password. Spaces are not allowed.');
//   } else {
//     console.log('Valid password');
//   }
// } else {
//   console.log('Password is too short. Min 8 chars required.');
// }

// let loggedInUser = 'user';

// if (loggedInUser) {
//   console.log('Welcome');
// } else {
//   console.log('Please log in');
// }

// let age = 23;

// if (age >= 18 && age < 21) {
//   console.log("You can enter and but can't drink");
// } else if (age >= 21 && age < 65) {
//   console.log('You can enter and drink');
// } else if (age > 65) {
//   console.log('Drinks are free');
// } else {
//   console.log('You are not allowed');
// }

// let day = 40;

// if (day === 1) {
//   console.log('Mon');
// } else if (day === 2) {
//   console.log('Tue');
// } else if (day === 3) {
//   console.log('Wed');
// } else if (day === 4) {
//   console.log('Thu');
// } else if (day === 5) {
//   console.log('Fri');
// } else if (day === 6) {
//   console.log('Sat');
// } else if (day === 7) {
//   console.log('Sun');
// } else {
//   console.log('Invalid day number');
// }

// let day = 5;

// switch (day) {
//   case 1:
//     console.log('Mon');
//     break;
//   case 2:
//     console.log('Tue');
//     break;
//   case 3:
//     console.log('Wed');
//     break;
//   case 4:
//     console.log('Thu');
//     break;
//   case 5:
//     console.log('Fri');
//     break;
//   case 6:
//     console.log('Sat');
//     break;
//   case 7:
//     console.log('Sun');
//     break;
//   default:
//     console.log('Invalid day number');
// }

let role = 'admin';

// if (role === 'admin') {
//   console.log('Access granted');
// } else {
//   console.log('Access denied');
// }

// role === 'admin' ? console.log('Access granted') : console.log('Access denied');

// let isAllowed;
// if (role === 'admin') {
//   isAllowed = true;
// } else {
//   isAllowed = false;
// }

let isAllowed = role === 'admin' ? true : role === 'mod' ? 'maybe' : false;

console.log(isAllowed);

let age = 10;

age >= 18 && age < 21
  ? console.log('You can enter but not drink')
  : age >= 21 && age < 65
  ? console.log('You can drink')
  : age > 65
  ? console.log('Drinks are free')
  : console.log("Can't Enter");

Scratchpad #4

// let age = 19;

// age >= 18 ? console.log("You can enter") : age >= 21 ? console.log("") : console.log("")

// if (age >= 18) {
//   console.log("")
// } else if ()

// recycleBin.push('john')

// const nums = [[1,2,3], [4,5,6], [7,8,9]];

const product1 = [1, 'iPhone', 'Apple', 100000, 200, 'Some description...'];
const product2 = [2, 'Nord', 'One Plus', 500000, 1000, 'Some description...'];
const product3 = [65, 'One Plus', 'Nord', 1000, 500000, 'Some description...'];

const products = [product1, product2];

products[-1];

let product5 = {
  price: 100000,
  name: 'iPhone',
  brand: 'Apple',
  inStock: 200,
  description: 'Some description...',
  srNo: 1,
  100: true,
  'hello world': 'good',
};

// product4.price;

// let nums = ['john', 'jane', 'jack'];

// let nums = { 0: 'john', 1: 'jane', 2: 'jack', length: 3 };

// const product3 = [65, 'One Plus', 'Nord', 1000, 500000, 'Some description...'];

// const product4 = {0: 65, 1: 'One Plus', 2: 1000, 3: 50000}

Scratchpad #5

// const shoppingCart = [
//   {
//     product: 'Apple iPhone',
//     price: 100000,
//     quantity: 100,
//   },
//   {
//     product: 'One Plus Nord',
//     price: 60000,
//     quantity: 1000,
//   },
//   {
//     product: 'Alienware M15',
//     price: 299999,
//     quantity: 1,
//   },
// ];

// console.log(shoppingCart[0].price);

// const song = {
//   name: 'song #1',
//   album: 'album #2',
//   artists: [
//     {
//       name: 'person 1',
//       dob: '12/12/2000',
//     },
//     {
//       name: 'person 1',
//       dob: '12/12/2000',
//     },
//   ],
// };

// for (let i = 0; i <= 10; i++) {
//   console.log(`${i} - hello world`);
// }

// for (let i = 10; i > 0; i--) {
//   console.log(`${i} - hello world`);
// }

// for (let i = 10; i > 0; i++) {
//   console.log(i ** 2);
// }

// const nums = [12, 34, 56, 34, 78, 54, 23, 12];

// for (let i = 0; i < nums.length; i++) {
//   console.log(`The number at index ${i} is ${nums[i]}`);
// }

// const movies = [
//   { movieName: 'Inception', rating: 3.8 },
//   { movieName: 'Avengers', rating: 3.4 },
//   { movieName: 'Iron Man', rating: 2.9 },
// ];

// for (let i = 0; i < movies.length; i++) {
//   const movie = movies[i];
//   console.log(`The movie ${movie.movieName} has a rating of ${movie.rating}`);
// }

// const word = 'Hello World';
// let reversedWord = '';

// for (let i = word.length - 1; i >= 0; i--) {
//   // console.log(word[i]);
//   reversedWord += word[i];
// }

// console.log(reversedWord);

// for (let i = 0; i < 5; i++) {
//   console.log(`${i} - outer loop`);

//   for (let j = 0; j < 5; j++) {
//     console.log(`     ${j} - inner loop`);
//   }
// }

// const a = [4, 64, 8, 4];

// let total = 0;

// for (let i = 0; i < a.length; i++) {
//   total += a[i];
// }

// console.log(total);

// const gameBoard = [
//   [4, 64, 8, 4],
//   [128, 32, 4, 16],
//   [16, 4, 4, 32],
//   [2, 16, 16, 2],
// ];

// let total = 0;

// for (let i = 0; i < gameBoard.length; i++) {
//   // console.log(gameBoard[i]);

//   for (let j = 0; j < gameBoard[i].length; j++) {
//     // console.log(gameBoard[i][j]);
//     total += gameBoard[i][j];
//   }
// }

// console.log(total);

// const gameBoard = [
//   [
//     [4, 64, 8, 4],
//     [4, 64, 8, 4],
//     [4, 64, 8, 4],
//     [4, 64, 8, 4],
//   ],
//   [
//     [4, 64, 8, 4],
//     [4, 64, 8, 4],
//     [4, 64, 8, 4],
//     [4, 64, 8, 4],
//   ],
//   [
//     [4, 64, 8, 4],
//     [4, 64, 8, 4],
//     [4, 64, 8, 4],
//     [4, 64, 8, 4],
//   ],
//   [
//     [4, 64, 8, 4],
//     [4, 64, 8, 4],
//     [4, 64, 8, 4],
//     [4, 64, 8, 4],
//   ],
// ];

// for (let i = 0; i < 10; i++) {
//   console.log(i);
// }

// let j = 0;

// while (j < 10) {
//   console.log(j);
//   j++;
// }

// const randomNum = Math.floor(Math.random() * 100) + 1;
// let guess = Math.floor(Math.random() * 100) + 1;

// while (guess !== randomNum) {
//   console.log(`Random Number: ${randomNum} | Guess: ${guess}`);
//   guess = Math.floor(Math.random() * 100) + 1;
// }

// console.log(`GAME OVER\nRandom Number: ${randomNum} | Guess: ${guess}`);

// let i = 0;

// while (i < 20) {
//   console.log(i);
//   if (i === 15) {
//     break;
//   }
//   i++;
// }

// const randomNum = Math.floor(Math.random() * 100) + 1;
// let guess = Math.floor(Math.random() * 100) + 1;

// while (true) {
//   console.log(`Random Number: ${randomNum} | Guess: ${guess}`);

//   if (guess === randomNum) {
//     break;
//   }

//   guess = Math.floor(Math.random() * 100) + 1;
// }

// console.log(`GAME OVER\nRandom Number: ${randomNum} | Guess: ${guess}`);

// const nums = [12, 34, 56, 34, 78, 54, 23, 12];

// // for (let i = 0; i < nums.length; i++) {
// //   console.log(nums[i]);
// // }

// for (let num of nums) {
//   console.log(num);
// }

// for (let char of 'Hello') {
//   console.log(char.toUpperCase());
// }

// const matrix = [
//   [1, 4, 7],
//   [9, 7, 2],
//   [9, 4, 6],
// ];

// for (let row of matrix) {
//   for (let col of row) {
//     console.log(col);
//   }
// }

// const cats = ['fashion', 'mobiles', 'books'];
// const prods = ['tshirt', 'samsung', '1984'];

// for (let i = 0; i < cats.length; i++) {
//   console.log(cats[i], prods[i]);
// }

// const productPrices = {
//   Apple: 80000,
//   OnePlus: 50000,
//   Samsung: 90000,
// };

// for (let key of Object.keys(productPrices)) {
//   console.log(`The cost of ${key} is ${productPrices[key]}`);
// }

// for (let val of Object.values(productPrices)) {
//   console.log(val);
// }

// for (let key in productPrices) {
//   console.log(productPrices[key]);
// }

const movieRating = {
  pursuitOfHappiness: 4.8,
  satya: 4.8,
  gangsOfWasepur: 4,
  robot: -3,
};

for (let movie of Object.keys(movieRating)) {
  console.log(movieRating[movie]);
}

for (let movie in movieRating) {
  console.log(movieRating[movie]);
}

Scratchpad #6

// function greet() {
//   console.log('Hello World');
//   console.log('Hello World');
//   console.log('Hello World');
// }

// // greet();
// // greet();

// // for (let i = 0; i < 50; i++) {
// //   greet();
// // }

// greet();

// function rollDie() {
//   let roll = Math.floor(Math.random() * 6) + 1;
//   console.log(`Rolled: ${roll}`);
// }

// function rollDice() {
//   rollDie();
//   rollDie();
//   rollDie();
// }

// // rollDie();

// rollDice();

// function greet(name) {
//   console.log(`Hello, ${name}`);
// }

// greet('John');
// greet('Jane');

// function rollDice(times) {
//   for (let i = 0; i < times; i++) {
//     rollDie();
//   }
// }

// rollDice(5);

// let score = 0;

// function greet(name, message) {
//   console.log(`${message}, ${name}`);
//   score += 100;
// }

// greet('John', 'Hello');
// greet('John', 'Hello');

// console.log(score);

// function add(a, b) {
//   return a + b;
// }

// // add(10, 5);

// let result = add(10, 10);

// console.log(result);

// function isNumber(val) {
//   if (typeof val === 'number') {
//     return true;
//   } else {
//     return false;
//   }
// }

// console.log(isNumber('5'));

// let score = 20;

// function increaseScore(val) {
//   score += val;
//   return score;
// }

// console.log(increaseScore(10));
// console.log(increaseScore(5));

// function incrementScore(currScore, val) {
//   return currScore + val;
// }

// score = incrementScore(score, 10);

// console.log(score);

// let fullName = 'Jane Doe';

// function greet() {
//   let fullName = 'Jack Smith';
//   console.log(fullName);
// }

// console.log(fullName);

// // greet();

// if (true) {
//   var firstName = 'John';
//   var lastName = 'Doe';
//   var fullName = firstName + ' ' + lastName;
// }

// console.log(fullName);

// for (var i = 0; i < 10; i++) {
//   console.log(i);
// }

// // console.log(i);

// let name = 'John';
// let name = 'Doe';

// console.log(name);

// function outer() {
//   // let movie = 'Dr. Strange';

//   function inner() {
//     let movie = 'Thor';
//     let rating = `${movie} has a rating of 4.2`;
//     console.log(rating);
//   }

//   console.log(movie);

//   inner();
// }

// outer();

// function add(a, b) {
//   return a + b;
// // }

// const add = function (a, b) {
//   return a + b;
// };

// // let score = 100;

// console.log(add(10, 5));

// function math(a, b, fn) {
//   return fn(a, b);
// }

// function add(a, b) {
//   return a + b;
// }

// console.log(math(10, 5, add));

// console.log(
//   math(10, 20, function (a, b) {
//     return a * b;
//   })
// );

// const myfuncs = [
//   function (a, b) {
//     return a + b;
//   },
//   function (a, b) {
//     return a - b;
//   },
//   function (a, b) {
//     return a * b;
//   },
//   function (a, b) {
//     return a / b;
//   },
// ];

// console.log(myfuncs[0](10, 5));
// console.log(myfuncs[1](10, 5));
// console.log(myfuncs[2](10, 5));
// console.log(myfuncs[3](10, 5));

// const math = {
//   add: function (a, b) {
//     return a + b;
//   },
//   sub: function (a, b) {
//     return a - b;
//   },
//   mul: function (a, b) {
//     return a * b;
//   },
//   div: function (a, b) {
//     return a / b;
//   },
// };

// console.log(math.add(100, 50));

// Math.random();

// const console = {
//   log: function () {},
//   error: function () {},
// };

// function multipleGreets(fn) {
//   fn();
//   fn();
//   fn();
// }

// function sayHello() {
//   console.log('Hello World!');
// }
// function sayGoodbye() {
//   console.log('Bye World!');
// }

// multipleGreets(sayHello);
// multipleGreets(sayGoodbye);

// function repeat(func, num) {
//   for (let i = 0; i < num; i++) {
//     func()
//   }
// }

// function sayHello() {
//   console.log('Hello World!')
// }
// function sayGoodbye() {
//   console.log('Bye World!')
// }

// repeat(sayHello, 10)
// repeat(sayGoodbye, 5)

// function randomPick(f1, f2) {
//   let randNum = Math.random();
//   if (randNum < 0.5) {
//     f1();
//   } else {
//     f2();
//   }
// }

// randomPick(sayHello, sayGoodbye);

function raiseBy(val) {
  return function (x) {
    return x ** val;
  };
}

const square = raiseBy(2);
const cube = raiseBy(3);
const tesseract = raiseBy(4);

console.log(test(2));

Scratchpad #7

// function logHello() {
//   console.log('Hello World');
// }

// setTimeout(logHello, 5000);

// setTimeout(function () {
//   console.log('Hello after 3 seconds');
// }, 3000);

// function greet() {
//   console.log('Hello World');
// }

// greet();

// let fullName = 'John Doe';

// console.log(fullName);

// const nums = [9, 2, 4, 6, 2, 3, 7, 6];

// for (let i = 0; i < nums.length; i++) {
//   console.log(nums[i]);
// }

// for (let num of nums) {
//   console.log(num);
// }

// nums.forEach(function (num) {
//   if (num % 2 === 0) {
//     console.log(num * num);
//   }
// });

// const names = ['john', 'jack', 'jane', 'james', 'jim'];

// names.forEach(function (name, i) {
//   console.log(`${i + 1} - ${name}`);
// });

// const movies = [
//   {
//     title: 'Avengers',
//     rating: 4.1,
//   },
//   {
//     title: 'Dr. Strange',
//     rating: 3.9,
//   },
//   {
//     title: 'Tenet',
//     rating: 4.3,
//   },
//   {
//     title: 'Joker',
//     rating: 4.7,
//   },
// ];

// // using forEach method
// movies.forEach(function (movie) {
//   console.log(movie.title.toUpperCase());
// });

// // Using for..of loop
// for (let movie of movies) {
//   console.log(movie.title.toUpperCase());
// }

// // if we want the index no.
// // second arg is the index value
// movies.forEach(function (movie, idx) {
//   console.log(`Movie ${idx}) ${movie.title} has a rating of ${movie.rating}`);
// });

// const names = ['john', 'jack', 'jane', 'james'];

// const uppercasedNames = names.map(function (name) {
//   return name.toUpperCase();
// });

// console.log(uppercasedNames);

// const names = ['john', 'jack', 'jane', 'james'];
// const uppercasedNames = [];

// for (let name of names) {
//   uppercasedNames.push(name.toUpperCase());
// }

// console.log(uppercasedNames);

// const nums = [2, 3, 4, 7, 6, 8, 13, 10, 19, 12, 14, 22, 21, 16];

// const doubles = nums.map(function (num) {
//   return num * 2; // we have to return a value
// });

// console.log(doubles);

// const numDetails = nums.map(function (num) {
//   return {
//     number: num,
//     isEven: num % 2 === 0,
//   };
// });

// console.log(numDetails);

// const nums = [2, 3, 4, 7, 6, 8, 13, 10, 19, 12, 14, 22, 21, 16];

// const doubles = nums.map(function (num) {
//   return num * 2;
// });

// console.log(doubles);

// const square = function (x) {
//   return x ** 2;
// };

// const square = (x) => {
//   return x ** 2;
// };

// const square = x => {
//   return x ** 2;
// };

// const square = x => (
//   x ** 2
// );

// const square = x => (x ** 2);

// const square = x => x ** 2;

// console.log(square(10));

// const nums = [2, 3, 4, 7, 6, 8, 13, 10, 19, 12, 14, 22, 21, 16];

// // const doubles = nums.map(function (num) {
// //   return num * 2;
// // });

// const doubles = nums.map(num => num * 2);

// console.log(doubles);

// const isEven = function(num) { // regular function expression
//   return num % 2 === 0
// }
// const isEven = (num) => { // arrow function with parens around single param
//   return num % 2 === 0
// }
// const isEven = num => { // no parens around param
//   return num % 2 === 0
// }
// const isEven = num => ( // parens in-place of braces. Implicit return.
//   num % 2 === 0
// )
// const isEven = num => num % 2 === 0 // one-liner implicit return

// const nums = [1, 2, 3, 4, 5, 6];

// // using regular function expressions
// const doubles1 = nums.map(function (n) {
//   return n * 2;
// });

// // using arrow functions
// const doubles2 = nums.map((n) => {
//   return n * 2;
// });

// // using arrow function's one-liner implicit return
// const doubles3 = nums.map((n) => n * 2);
// const parityList = nums.map((n) => (n % 2 === 0 ? 'Even' : 'Odd'));

// let movies = ['The Terminator', 'The Avengers', 'Jurassic Park', 'Titanic'];

// // let result = movies.find((movie) => movie === 'titanic');

// let result = movies.find((movie) => movie.toLowerCase().includes('e'));

// console.log(result);

// const books = [
//   {
//     title: 'The Shining',
//     author: 'Stephen King',
//     rating: 4.1,
//   },
//   {
//     title: 'Sacred Games',
//     author: 'Vikram Chandra',
//     rating: 4.5,
//   },
//   {
//     title: '1984',
//     author: 'George Orwell',
//     rating: 4.9,
//   },
//   {
//     title: 'The Alchemist',
//     author: 'Paulo Coelho',
//     rating: 3.5,
//   },
//   {
//     title: 'The Great Gatsby',
//     author: 'F. Scott Fitzgerald',
//     rating: 3.8,
//   },
// ];

// console.log(books.sort((a, b) => b.rating - a.rating));

// // const result = books.find((book) => book.rating < 4);
// // const result = books.find((book) => book.author.includes('Stephen'));

// const result = books.filter((book) => book.rating < 4);
// console.log(result);

// const goodBook = books.filter((b) => b.rating >= 4.3);

// const georgeBooks = books.filter((b) => b.author.includes('George'));

// const lowRated = books.filter((book) => {
//   return book.rating < 4;
// });

// let query = 'the';

// const filteredBooks = books.filter((book) => {
//   return book.title.toLowerCase().includes(query);
// });

// console.log(goodBook);
// console.log(georgeBooks);
// console.log(lowRated);
// console.log(filteredBooks);

// const names = ['jack', 'james', 'john', 'jane', 'josh', 'brad'];

// // const result = names.every((name) => name[0] === 'j');
// // console.log(result);

// // const result = names.every((name) => name[name.length - 1] !== 'a');
// // console.log(result);

// const result = names.some((name) => name[0] === 'b');

// console.log(result);

// const prices = [500.4, 211, 23, 5, 4, 22.2, -23.2, 9233];

// console.log(prices.sort((a, b) => a - b));
// console.log(prices.sort((a, b) => b - a));

// const nums = [1, 2, 3, 4, 5, 6];

// const res = nums.reduce((acc, currVal) => {
//   return acc + currVal;
// }, 100);

// console.log(res);

// ACC      CURRVAL
// 1        2
// 3        3
// 6        4
// 10       5
// 15       6
// 21

// 21

// let nums = [21, 221, 2, 1, 34, 123, 4342, 56, 4];

// const maxVal = nums.reduce((acc, currentVal) => {
//   if (currentVal > acc) {
//     return currentVal;
//   }
//   return acc;
// });

// console.log(maxVal);

// ACC    CURRVAL
// 21     221
// 221    2
// 221    1
// 221    34
// 221    4342
// 4342

// const maxVal = nums.reduce((max, currVal) => Math.max(max, currVal));
// console.log(maxVal);

// const color = 'red';

// color === 'red'
//   ? console.log('DANGER')
//   : color === 'yellow'
//   ? console.log('WARNING')
//   : color === 'orange'
//   ? console.log('SOMETHING')
//   : console.log('OK');

Scratchpad #8

// const multiply = (a = 1, b = 1) => {
//   return a * b;
// };

// const multiply = (a, b) => {
//   console.log(arguments);
//   return a * b;
// };

// console.log(multiply(10, 2, 5, 50));

// function multiply(a = 1, b = 1) {
//   // if (typeof a === 'undefined') {
//   //   a = 1;
//   // }
//   // if (typeof b === 'undefined') {
//   //   b = 1;
//   // }
//   return a * b;
// }
// console.log(multiply(10));

// const greet = (name = 'John') => {
//   console.log(`Hello my name is ${name}`);
// };

// greet();

// const multiply = (a, b = 1) => {
//   return a * b;
// };

// console.log(multiply(10));

// function printVals(a, b, c) {
//   console.log(a);
//   console.log(b);
//   console.log(c);
// }

// // const names = ['John', 'Jane', 'jack', 'nsdkjandssad'];

// // printVals(...names);

// printVals(...'John');

// const add = (...nums) => {
//   // console.log(nums);

//   // let total = 0;
//   // for (let num of nums) {
//   //   total += num;
//   // }
//   // return total;

//   // let total = 0;
//   // nums.forEach((num) => (total += num));
//   // return total;

//   return nums.reduce((acc, currVal) => acc + currVal);
// };

// console.log(add(10, 5, 50, 12, 34, 23));

// function printNames(name1, name2, ...others) {
//   console.log(name1);
//   console.log(name2);
//   console.log(others);
// }

// printNames('John', 'jane', 'Jack', 'James', 'Jim', 'Joey', 'Jagdish', 'Jeevan');

// const users = ['john', 'jane', 'jack'];

// const admin = users[0];
// const mod = users[1];
// const sub = users[2];

// const [admin, mod, sub] = users;
// const [admin, ...others] = users;

// const [, , sub] = users;

// console.log(admin);
// console.log(mod);
// console.log(sub);

// console.log(others);

// const user = {
//   firstName: 'John',
//   lastName: 'Doe',
//   email: 'john.doe@gmail.com',
//   phone: 99982234567,
// };

// const { email: emailAddress, phone } = user;

// // console.log(firstName);
// // console.log(lastName);
// console.log(emailAddress);
// console.log(phone);

// const profile = (user) => {
//   console.log(`My name is ${user.name} and I am ${user.age} years old.`);
//   console.log(`I work as a ${user.job} at ${user.company}.`);
// };

// const profile = ({ name, age: umer, job, company }) => {
//   console.log(`My name is ${name} and I am ${umer} years old.`);
//   console.log(`I work as a ${job} at ${company}.`);
// };

// profile({
//   name: 'John Doe',
//   age: 25,
//   job: 'Full Stack Dev',
//   company: 'Google',
// });

// const movieReviews = [4.5, 5.0, 3.2, 2.1, 4.7, 3.8, 3.1, 3.9, 4.4];
// const highest = Math.max(...movieReviews);
// const lowest = Math.min(...movieReviews);

// let total = 0;
// movieReviews.forEach((rating) => (total += rating));
// const average = total / movieReviews.length;

// const info1 = { highest, lowest: 0, average };

// console.log(info1);

// const getReviewDetails = (arr) => {
//   const highest = Math.max(...arr)
//   const lowest = Math.min(...arr)
//   const total = arr.reduce((accumulator, nextVal) => accumulator + nextVal)
//   const average = total / arr.length

//   return {
//     highest,
//     lowest,
//     total,
//     average
//   }
// }

// const reviewList = [4.5, 5.0, 3.2, 2.1, 4.7, 3.8, 3.1, 3.9, 4.4]

// const statistics = getReviewDetails(reviewList)

// const username = 'janedoe';
// const role = 'admin';

// const user1 = { [role]: username };

// console.log(user1);

// const addProperty = (obj, k, v) => {
//   return { ...obj, [k.toUpperCase()]: v };
// };

// console.log(addProperty({ name: 'John' }, 'age', 25));

// const math = {
//   multiply: function (x, y) {
//     return x * y;
//   },
//   divide: function (x, y) {
//     return x / y;
//   },
//   subtract: function (x) {
//     return x - x;
//   },
// };

// console.log(math.subtract(10, 5));

// function square(x) {
//   return x * x;
// }

// const math = {
//   multiply: function (x, y) {
//     return x * y;
//   },
//   divide: function (x, y) {
//     return x / y;
//   },
//   subtract: function (x) {
//     return x - x;
//   },
//   square,
// };

// const math = {
//   multiply(x, y) {
//     return x * y;
//   },
//   divide(x, y) {
//     return x / y;
//   },
//   subtract(x) {
//     return x - x;
//   },
//   square,
// };

// console.log(math.square(10));

// console.log(this);

// console.log('Hello World');

// function namaste() {
//   console.log(this);
//   console.log('Hello World');
// }

// namaste();

const profile = {
  name: 'John Doe',
  greet: function () {
    console.log(this.name);
  },
  something: {
    hello: function () {
      console.log(this);
    },
  },
};

console.log(profile.something.hello());

// const namaskar = 'Hello';

// console.log(this.alert());

// console.log(this);

// profile.greet();

// alert('Hello World');

Scratchpad #9

// // const user = {
// //   firstName: 'John',
// //   lastName: 'Doe',
// //   role: 'admin',
// //   fullName() {
// //     console.log(this);
// //   },
// // };

// // const sayFullName = user.fullName;

// // // user.fullName();

// // // console.log(sayFullName);

// // user.fullName();
// // sayFullName();

// // const user = {
// //   firstName: 'John',
// //   lastName: 'Doe',
// //   role: 'admin',
// //   fullName() {
// //     const { firstName, lastName, role } = this;
// //     console.log(`${firstName} ${lastName} is an ${role}`);
// //   },
// // };

// // const user2 = {
// //   firstName: 'Jane',
// //   lastName: 'Smith',
// //   role: 'moderator',
// //   fullName: user.fullName,
// // };

// // user2.fullName();

// const user = {
//   firstName: 'John',
//   lastName: 'Doe',
//   role: 'admin',
//   fullName() {
//     return `${this.firstName} ${this.lastName} is an ${this.role}`;
//   },
//   logDetails() {
//     console.log(`${this.fullName()} and is cool!`);
//   },
// };

// const logDetails = user.logDetails;

// logDetails();

// const hellos = {
//   messages: [
//     'hello world',
//     'hello universe',
//     'hello darkness',
//     'hello hello',
//     'heylo',
//   ],
//   pickMsg() {
//     const index = Math.floor(Math.random() * this.messages.length);
//     return this.messages[index];
//   },
//   start() {
//     console.log(this)
//     setInterval(() => console.log(this.pickMsg()), 1000);
//   },
// };

// console.log(hellos.pickMsg());

// setInterval(function () {
//   console.log('Hello', Math.random());
// }, 2000);

// hellos.start();

// const user = {
//   firstName: 'John',
//   lastName: 'Doe',
//   role: 'admin',
//   fullName: () => {
//     return `${this.firstName} ${this.lastName} is an ${this.role}`;
//   },
// };

// console.log(user.fullName());

// console.dir(document.body);

// const title = document.getElementById('info');

// console.dir(title.innerText);
// // title.innerText = 'Hello World';

// setInterval(function () {
//   title.innerText = Math.random();
// }, 1000);

// const paras = document.getElementsByTagName('p');

// console.dir(paras);

// const blues = document.getElementsByClassName('intro-title');

// console.dir(blues);

// const ul = document.getElementsByClassName('lst')[0];

// const lis = ul.getElementsByTagName('li');
// console.log(lis);

// const ul = document.querySelector('.lst');
// const title = document.querySelector('#info');
// const paras = document.querySelectorAll('p');

// console.dir(ul);
// console.dir(title);

// console.dir(paras);

// const h3 = document.querySelector('h3');
// console.dir(h3.innerText);
// h3.innerText = 'Hello <i>Universe</i>';
// h3.innerHTML = 'Hello <i>Universe</i>';
// h3.innerHTML += ' Hello <em>World</em>.';

// const ul = document.querySelector('ul');
// console.log(ul.innerHTML);
// console.log(ul.textContent);
// ul.innerText = 'Hello World';

// const special = document.querySelector('.special');
// console.log(special.innerHTML);

const input = document.querySelector('input');

input.value = 'Something else';
// console.dir(input.value);

const img = document.querySelector('img');
console.dir(img);
img.width = 200;
// img.height = 200;

console.log(img.src);

img.src =
  'https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png';

const checkbox = document.querySelector('#check');

console.log(checkbox.checked);
checkbox.checked = true;

Scratchpad #10

// const title = document.querySelector('.intro-title');

// title.innerText = 'Hello';
// title.style = 'border: 1px solid red';

// const range = document.querySelector('input[type="range"]');

// // console.dir(range.getAttribute('max'));

// range.min = 100;
// range.setAttribute('min', 100);

// console.log(range.getAttribute('min'));

// range.setAttribute('type', 'radio');

// const li = document.querySelector('.imp-li');
// const ul = li.parentElement;

// console.dir(li.parentElement.parentElement);

// console.dir(ul.children[4]);

// console.dir(
//   ul.previousElementSibling.previousElementSibling.previousElementSibling
// );

// const lis = document.querySelectorAll('li');

// for (let li of lis) {
//   setInterval(function () {
//     li.innerText = Math.random();
//   }, Math.floor(Math.random() * 1000)) - 1;
// }

// const title = document.querySelector('.intro-title');

// console.log(title.style.textDecoration);

// title.style.textDecoration = 'underline';
// title.style.color = 'purple';
// title.style.fontWeight = '300';

// function applyStyles(el, styles) {
//   for (let key in styles) {
//     el.style[key] = styles[key];
//   }
// }

// const myStyle = {
//   fontSize: '40px',
//   textDecoration: 'overline',
//   color: 'green',
// };

// applyStyles(title, myStyle);

// const titleStyles = getComputedStyle(title);

// console.log(titleStyles.color);

// const li = document.querySelector('li');
// li.setAttribute('class', 'todo done');

// li.setAttribute('class', 'done');

// console.dir(li.classList);

// li.classList.toggle('done');

// const h1 = document.createElement('h1');
// h1.innerText = 'This is a new title';
// h1.style.color = 'green';

// const div = document.createElement('div');
// div.style.border = '5px solid black';
// div.style.padding = '50px';
// div.appendChild(h1);

// const root = document.querySelector('#root');
// root.appendChild(div);

// const ul = document.querySelector('ul');

// const task = document.createElement('li');
// task.innerText = 'This is a new task.';

// const firstTask = ul.querySelector('li');

// // ul.appendChild(task);

// ul.insertBefore(task, firstTask);

// const p = document.querySelector('p');

// const b = document.createElement('b');
// b.innerText = 'BOLD TEXT';

// p.insertAdjacentElement('afterend', b);

// const b = document.createElement('b');
// b.innerText = 'HELLO WORLD';
// const i = document.createElement('i');
// i.innerText = 'GOODBYE GALAXY';

// const p = document.querySelector('p');

// p.prepend(b, i);

// const ul = document.querySelector('ul');

// const li1 = document.querySelectorAll('li')[0];
// const li2 = document.querySelectorAll('li')[1];

// // ul.removeChild(li1);
// // ul.removeChild(li2);

// li1.remove();
// ul.remove();

// const root = document.querySelector('#root');

// const btn = document.querySelector('button');

// btn.onclick = function () {
//   const p = document.createElement('p');
//   p.innerText = Math.random();
//   root.appendChild(p);
// };

// btn.addEventListener('click', function () {
//   const p = document.createElement('p');
//   p.innerText = Math.random();
//   root.appendChild(p);
// });

// btn.addEventListener('mouseover', function () {
//   const body = document.querySelector('body');
//   body.style.backgroundColor = 'red';
// });

// const div = document.querySelector('div');

// // console.log(div);

// const body = document.querySelector('body');

// window.addEventListener('scroll', () => {
//   // const p = document.createElement('p');
//   // p.innerText = Math.random();
//   // div.appendChild(p);
//   console.log('Scroll');
// });

// btn.addEventListener('mouseover', function () {
//   btn.innerText = 'Button Hovered!';
// });

// btn.addEventListener('mouseout', function () {
//   btn.innerText = 'Click me';
// });

// const btn = document.querySelector('button');

// btn.addEventListener('mouseover', function () {
//   const height = Math.floor(Math.random() * window.innerHeight);
//   const width = Math.floor(Math.random() * window.innerWidth);
//   btn.style.left = `${width}px`;
//   btn.style.top = `${height}px`;
// });

// btn.addEventListener('click', function () {
//   btn.innerText = 'You Won!';
//   document.body.style.backgroundColor = 'green';
// });

// const colors = [
//   'red',
//   'orange',
//   'yellow',
//   'green',
//   'blue',
//   'purple',
//   'indigo',
//   'violet',
// ];

// const container = document.querySelector('#boxes'); // Select the container
// const span = document.querySelector('span');

// const printColor = function () {
//   span.innerText = this.style.backgroundColor;
//   document.body.style.backgroundColor = this.style.backgroundColor;
// };

// // Loop to add each color as a background color (create as many boxes as length of colors)
// for (let color of colors) {
//   const box = document.createElement('div'); // Create a square box

//   box.style.backgroundColor = color; // Style the box
//   box.classList.add('box'); // Add a class

//   container.append(box); // Append box to container

//   // Add event listener to the box
//   box.addEventListener('click', printColor);
// }

// // Change other elements on the DOM
// const changeColor = function () {
//   const h1 = document.querySelector('h1')
//   h1.style.color = this.style.backgroundColor
//   h1.innerText = this.style.backgroundColor + ' selected'
// }

// for (let color of colors) {
//   const box = document.createElement('div') // Create a square box

//   box.style.backgroundColor = color // Style the box
//   box.classList.add('box') // Add a class

//   container.append(box) // Append box to container

//   // Add event listener to the box
//   box.addEventListener('click', printColor)
//   box.addEventListener('click', changeColor)
// }

// const btn = document.querySelector('button');
// const p = document.querySelector('p');

// btn.addEventListener('click', function (event) {
//   console.log(event.target);
// });

// const input = document.querySelector('input');

// input.addEventListener('keyup', function (event) {
//   console.log(event);
//   p.innerText = event.target.value.toUpperCase();
// });

const input = document.querySelector('input');
const ul = document.querySelector('ul');

input.addEventListener('keypress', function (event) {
  const li = document.createElement('li');
  li.innerText = event.target.value;

  li.addEventListener('click', function () {
    // li.remove();
    li.style.textDecoration = 'line-through';
  });

  if (event.key === 'Enter') {
    ul.append(li);
    input.value = '';
  }
});

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      button {
        position: relative;
      }

      #boxes {
        display: flex;
      }

      .box {
        height: 200px;
        width: 200px;
      }
    </style>
  </head>
  <body>
    <!-- <ul id="todos">
      <li>
        First item. Lorem ipsum dolor sit amet consectetur adipisicing elit.
      </li>
      <li>
        Last item. Lorem ipsum dolor sit amet consectetur adipisicing elit.
      </li>
    </ul> -->

    <!-- <p>
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Amet obcaecati
      neque fugiat ratione eius temporibus veniam earum possimus iure? Officia
      autem, assumenda temporibus obcaecati odit laborum recusandae porro velit
      beatae.
    </p> -->

    <!-- <button>Click Me</button>
    <input type="text" />
    <p></p> -->

    <!-- <div id="boxes"></div> -->

    <div>
      <label for="task">Add task</label>
      <input type="text" id="task" />
    </div>
    <h2>My Tasks</h2>
    <ul></ul>

    <script src="./scratchpad_10.js"></script>
  </body>
</html>

Scratchpad #11

// const multiply = (x, y) => x * y;

// const square = (x) => multiply(x, x);

// const rightTriangle = (a, b, c) => {
//   return square(a) + square(b) === square(c);
// };

// rightTriangle(3, 4, 5);

// console.log('The first log');
// alert('An interruption in between');
// console.log('The last log');

// console.log('The first log');

// setTimeout(() => {
//   console.log('The line that takes time to complete');
// }, 3000);

// console.log('The last log');

// const btn = document.querySelector('button');

// setTimeout(() => {
//   btn.style.transform = `translateX(100px)`;
//   setTimeout(() => {
//     btn.style.transform = `translateX(200px)`;
//     setTimeout(() => {
//       btn.style.transform = `translateX(300px)`;
//       setTimeout(() => {
//         btn.style.transform = `translateX(400px)`;
//         setTimeout(() => {
//           btn.style.transform = `translateX(500px)`;
//           setTimeout(() => {
//             btn.style.transform = `translateX(600px)`;
//           }, 1000);
//         }, 1000);
//       }, 1000);
//     }, 1000);
//   }, 1000);
// }, 1000);

// const willGetAPlayStation = new Promise((resolve, reject) => {
//   const random = Math.random();

//   if (random > 0.5) {
//     resolve();
//   } else {
//     reject();
//   }
// });

// // console.log(willGetAPlayStation);

// willGetAPlayStation.then(() => {
//   console.log('Yayyy! Thank you!');
// });

// willGetAPlayStation.catch(() => {
//   console.log('Booo! F U');
// });

// const makePlayStationPromise = () => {
//   return new Promise((resolve, reject) => {
//     setTimeout(() => {
//       const rand = Math.random();
//       if (rand < 0.5) {
//         resolve('Awesome');
//       } else {
//         reject('Too bad');
//       }
//     }, 5000);
//   });
// };

// makePlayStationPromise()
//   .then((result) => {
//     console.log(result);
//     console.log('I got a playstation!');
//   })
//   .catch((error) => {
//     console.log(error);
//     console.log("$@#$% I didn't get anything!");
//   });

// const fakeRequest = (url) => {
//   return new Promise((resolve, reject) => {
//     setTimeout(() => {
//       const pages = {
//         '/users': [
//           { id: 1, username: 'john' },
//           { id: 2, username: 'jane' },
//         ],
//         '/about': 'This is the about page',
//       };

//       const data = pages[url];

//       if (data) {
//         resolve({ status: 200, data });
//       } else {
//         reject({ status: 404 });
//       }
//     }, 3000);
//   });
// };

// fakeRequest('/users')
//   .then((result) => console.log(result))
//   .catch((error) => console.log(error));

const fakeRequest = (url) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const pages = {
        '/users': [
          { id: 1, username: 'john' },
          { id: 2, username: 'jane' },
        ],
        '/users/1': {
          id: 1,
          username: 'johndoe',
          topPostId: 53231,
          city: 'mumbai',
        },
        '/users/5': {
          id: 1,
          username: 'janedoe',
          topPostId: 32443,
          city: 'pune',
        },
        '/posts/53231': {
          id: 1,
          title: 'Really amazing post',
          slug: 'really-amazing-post',
        },
      };
      const data = pages[url];

      if (data) {
        resolve({ status: 200, data });
      } else {
        reject({ status: 404 });
      }
    }, 1000);
  });
};

// fakeRequest('/users')
//   .then((res) => {
//     console.log('Got 1st data', res);
//     const user = res.data[0];
//     fakeRequest(`/users/${user.id}`)
//       .then((res) => {
//         console.log('Got 2nd data', res);
//         const topPostId = res.data.topPostId;
//         fakeRequest(`/posts/${topPostId}`)
//           .then((data) => {
//             console.log('Got final data', res);
//           })
//           .catch((err) => console.log(err));
//       })
//       .catch((err) => console.log(err));
//   })
//   .catch((err) => console.log(err));

fakeRequest('/users')
  .then((res) => {
    console.log('Got 1st data', res);
    const user = res.data[0];
    return fakeRequest(`/users/${user.id}`);
  })
  .then((res) => {
    console.log('Got 2nd data', res);
    const topPostId = res.data.topPostId;
    return fakeRequest(`/posts/${topPostId}`);
  })
  .then((res) => {
    console.log('Got final data', res);
  })
  .catch((err) => console.error(err));

Scratchpad #12

// // alert('Hello World');

// // fetch('https://swapi.dev/api/planets')
// //   .then((response) => {
// //     if (response.status !== 200) {
// //       throw new Error('Something went wrong');
// //     }
// //     return response.json();
// //   })
// //   .then((data) => {
// //     data.results.map((planet) => {
// //       console.log(planet.name);
// //     });
// //   })
// //   .catch((err) => {
// //     console.log('THIS IS AN ERROR', err);
// //   });

// // fetch('https://swapi.dev/api/planets')
// //   .then((response) => {
// //     if (response.status !== 200) {
// //       throw new Error('Something went wrong');
// //     }
// //     return response.json();
// //   })
// //   .then((data) => {
// //     const movie = data.results[0].films[0];
// //     return fetch(movie);
// //   })
// //   .then((response) => {
// //     if (response.status !== 200) {
// //       throw new Error('Something went wrong');
// //     }
// //     return response.json();
// //   })
// //   .then((data) => {
// //     const starship = data.starships[0];
// //     return fetch(starship);
// //   })
// //   .then((response) => {
// //     if (response.status !== 200) {
// //       throw new Error('Something went wrong');
// //     }
// //     return response.json();
// //   })
// //   .then((data) => {
// //     console.log(data);
// //   })
// //   .catch((err) => {
// //     console.log('THIS IS AN ERROR', err);
// //   });

// const checkStatusAndParse = (res) => {
//   if (!res.ok) {
//     throw new Error(`Status code error: ${res.status}`);
//   }
//   return res.json();
// };

// // fetch('https://swapi.dev/api/planets')
// //   .then(checkStatusAndParse)
// //   .then((data) => {
// //     const movie = data.results[0].films[0];
// //     return fetch(movie);
// //   })
// //   .then(checkStatusAndParse)
// //   .then((data) => {
// //     const starship = data.starships[0];
// //     return fetch(starship);
// //   })
// //   .then(checkStatusAndParse)
// //   .then((data) => {
// //     console.log(data);
// //   })
// //   .catch((err) => {
// //     console.log('THIS IS AN ERROR', err);
// //   });

// const container = document.querySelector('#root');
// container.style.display = 'grid';
// container.style.gridTemplateColumns = '1fr 1fr 1fr 1fr';
// container.style.gap = '10px';

// axios
//   .get('https://swapi.dev/api/planets')
//   .then((response) => {
//     const { data } = response;

//     data.results.map((planet) => {
//       const card = document.createElement('div');

//       const name = document.createElement('h4');
//       name.innerText = planet.name;

//       const list = document.createElement('ul');

//       const pop = document.createElement('li');
//       pop.innerHTML = `<strong>Population: </strong> ${planet.population}`;

//       const terrain = document.createElement('li');
//       terrain.innerHTML = `<strong>Terrain: </strong> ${planet.terrain}`;

//       list.append(pop, terrain);
//       card.append(name, list);

//       card.style.border = '1px solid black';
//       card.style.borderRadius = '10px';
//       card.style.padding = '10px';

//       container.append(card);
//     });
//   })
//   .catch((err) => console.log('THIS IS AN ERROR'));

const inp = document.querySelector('input');
const btn = document.querySelector('button');
const list = document.querySelector('#list');

btn.addEventListener('click', function () {
  const taskItem = document.createElement('div');
  const taskName = document.createElement('p');
  taskName.innerText = inp.value;
  taskName.style.margin = '0';
  taskName.classList.add('hello');

  const check = document.createElement('input');
  check.type = 'checkbox';
  check.addEventListener('click', function () {
    if (check.checked) {
      taskName.style.textDecoration = 'line-through';
      taskName.style.color = 'green';
    } else {
      taskName.style.textDecoration = 'none';
      taskName.style.color = 'black';
    }
  });

  const grp = document.createElement('div');
  grp.append(check, taskName);
  grp.style.display = 'flex';

  const delBtn = document.createElement('button');
  delBtn.innerText = 'Delete Task';
  delBtn.addEventListener('click', function () {
    taskItem.remove();
  });

  taskItem.append(grp, delBtn);
  taskItem.style.display = 'flex';
  taskItem.style.justifyContent = 'space-between';
  taskItem.style.padding = '5px 10px';
  taskItem.style.border = '1px solid rgba(0,0,0,0.2)';

  list.append(taskItem);
  inp.value = '';
});

Scratchpad #13

// // function greet() {
// //   console.log(`My name is ${this.firstName} ${this.lastName}`);
// // }

// // const user1 = {
// //   firstName: 'John',
// //   lastName: 'Doe',
// //   greet,
// // };

// // const user2 = {
// //   firstName: 'Jack',
// //   lastName: 'Smith',
// //   greet,
// // };

// // user1.greet();
// // user2.greet();

// // const btn = document.querySelector('button');

// // btn.addEventListener('click', function () {
// //   console.log('I was clicked!');
// // });
// // btn.addEventListener('mouseover', function () {
// //   console.log('I was hover on!');
// // });

// // const data = axios.get('https://swapi.dev/api/planets');

// // data.then((response) => {
// //   console.log(response.data);
// // });

// // function getData(url) {
// //   let film = null;

// //   axios
// //     .get(url)
// //     .then((res) => {
// //       film = res.data.results[0].films[0];
// //       return axios.get(film);
// //     })
// //     .then((res) => {
// //       console.log(res.data);
// //     });
// // }

// // getData('https://swapi.dev/api/planets');

// // async function greet() {
// //   const rand = Math.random();

// //   if (rand > 0.5) {
// //     return 'You win';
// //   }
// //   throw new Error();
// // }

// // function greet() {
// //   return new Promise((resolve, reject) => {
// //     const rand = Math.random();

// //     if (rand > 0.5) {
// //       resolve('You win');
// //     } else {
// //       reject('You lose');
// //     }
// //   });
// // }

// // greet()
// //   .then((data) => console.log(data))
// //   .catch((err) => console.log(err));

// // function getData(url) {
// //   axios
// //     .get(url)
// //     .then((res) => {
// //       film = res.data.results[0].films[0];
// //       return axios.get(film);
// //     })
// //     .then((res) => {
// //       console.log(res.data);
// //     });
// // }
// // const getData2 = async (url) => {
// //   const { data } = await axios.get(url);
// //   const film = await axios.get(data.results[0].films[0]);

// //   console.log(film.data);
// // };

// // async function getData2(url) {
// //   try {
// //     const { data } = await axios.get(url);
// //     const film = await axios.get(data.results[0].films[0]);
// //     console.log(film.data);
// //   } catch (err) {
// //     console.log('Inside catch', err);
// //   }
// // }

// // // getData2('https://swapi.dev/api/planasdts').catch((err) =>
// // //   console.log('SOMETHING WENT WRONG')
// // // );

// // getData2('https://swapi.dev/api/planasdts');

// // async function getPokemon() {
// //   const pokemon1Promise = axios.get('https://pokeapi.co/api/v2/pokemon/1');
// //   const pokemon2Promise = axios.get('https://pokeapi.co/api/v2/pokemon/2');
// //   const pokemon3Promise = axios.get('https://pokeapi.co/api/v2/pokemon/3');

// //   const results = await Promise.all([
// //     pokemon1Promise,
// //     pokemon2Promise,
// //     pokemon3Promise,
// //   ]);

// //   console.log(results);

// // const pokemon1 = await pokemon1Promise;
// // const pokemon2 = await pokemon2Promise;
// // const pokemon3 = await pokemon3Promise;

// // console.log(pokemon1.data);
// // console.log(pokemon2.data);
// // console.log(pokemon3.data);
// // }

// // getPokemon();

// // function initializeDeck() {
// //   const deck = [];
// //   const suits = ['hearts', 'diamonds', 'spades', 'clubs'];
// //   const values = '2,3,4,5,6,7,8,9,10,J,Q,K,A';

// //   for (let value of values.split(',')) {
// //     for (let suit of suits) {
// //       deck.push({ value, suit });
// //     }
// //   }
// //   return deck;
// // }

// // function drawCard(deck, drawnCards) {
// //   const card = deck.pop();
// //   drawnCards.push(card);
// //   return card;
// // }

// // function drawMultiple(numCards, deck, drawnCards) {
// //   const cards = [];
// //   for (let i = 0; i < numCards; i++) {
// //     cards.push(drawCard(deck, drawnCards));
// //   }
// //   return cards;
// // }

// // function shuffle(deck) {
// //   // loop over array backwards
// //   for (let i = deck.length - 1; i > 0; i--) {
// //     // pick random index before current element
// //     let j = Math.floor(Math.random() * (i + 1));
// //     [deck[i], deck[j]] = [deck[j], deck[i]];
// //   }
// //   return deck;
// // }

// // const deck = initializeDeck();
// // shuffle(deck);

// // const cardsInHand = [];

// // drawCard(deck, cardsInHand);
// // drawCard(deck, cardsInHand);

// // drawMultiple(2, deck, cardsInHand);

// // console.log(cardsInHand);

// // const makeDeck = () => {
// //   return {
// //     deck: [],
// //     drawnCards: [],
// //     suits: ['hearts', 'diamonds', 'spades', 'clubs'],
// //     values: '2,3,4,5,6,7,8,9,10,J,Q,K,A',
// //     initializeDeck() {
// //       const { suits, values, deck } = this;
// //       for (let value of values.split(',')) {
// //         for (let suit of suits) {
// //           deck.push({ value, suit });
// //         }
// //       }
// //       return deck;
// //     },
// //     drawCard() {
// //       const card = this.deck.pop();
// //       this.drawnCards.push(card);
// //       return card;
// //     },
// //     drawMultiple(numCards) {
// //       const cards = [];
// //       for (let i = 0; i < numCards; i++) {
// //         cards.push(this.drawCard());
// //       }
// //       return cards;
// //     },
// //     shuffle() {
// //       const { deck } = this;
// //       for (let i = deck.length - 1; i > 0; i--) {
// //         let j = Math.floor(Math.random() * (i + 1));
// //         [deck[i], deck[j]] = [deck[j], deck[i]];
// //       }
// //     },
// //   };
// // };

// // const deck1 = makeDeck();
// // const deck2 = makeDeck();
// // const deck3 = makeDeck();

// // console.log(deck1);
// // console.log(deck2);
// // console.log(deck3);

// // // deck1.initializeDeck();

// // // deck1.shuffle();

// // // deck1.drawMultiple(4);

// // // console.log(deck1);

// // function Person(firstName, lastName, age) {
// //   this.firstName = firstName;
// //   this.lastName = lastName;
// //   this.age = age;
// //   this.job = 'Programmer';
// // }

// // Person.prototype.sayName = function () {
// //   console.log(`My name is ${this.firstName} ${this.lastName}`);
// // };

// // Person.prototype.greet = 'Nice!';

// // function personFactory(firstName, lastName, age) {
// //   return {
// //     firstName,
// //     lastName,
// //     age,
// //     sayName() {
// //       console.log(`My name is ${this.firstName} ${this.lastName}`);
// //     },
// //   };
// // }

// // const user1 = new Person('John', 'Doe', 25);
// // // const user2 = new Person('Jack', 'Doe', 25);
// // const user2 = personFactory('Jack', 'Doe', 25);

// // console.log(user1);
// // console.log(user2);

// // user1.sayName();
// // user2.sayName();

// // function Person(firstName, lastName, age) {
// //   this.firstName = firstName;
// //   this.lastName = lastName;
// //   this.age = age;
// //   this.job = 'Programmer';
// // }

// // Person.prototype.sayName = function () {
// //   console.log(`My name is ${this.firstName} ${this.lastName}`);
// // };

// // class Person {
// //   constructor(firstName, lastName, age) {
// //     this.firstName = firstName;
// //     this.lastName = lastName;
// //     this.age = age;
// //     this.job = 'Programmer';
// //   }

// //   sayName() {
// //     console.log(`My name is ${this.firstName} ${this.lastName}`);
// //   }
// // }

// // const user1 = new Person('John', 'Doe', 25);

// // console.log(user1);

// class Deck {
//   constructor() {
//     this.deck = [];
//     this.drawnCards = [];
//     this.suits = ['hearts', 'diamonds', 'spades', 'clubs'];
//     this.values = '2,3,4,5,6,7,8,9,10,J,Q,K,A';
//   }

//   initializeDeck() {
//     const { suits, values, deck } = this;
//     for (let value of values.split(',')) {
//       for (let suit of suits) {
//         deck.push({ value, suit });
//       }
//     }
//     return deck;
//   }

//   drawCard() {
//     const card = this.deck.pop();
//     this.drawnCards.push(card);
//     return card;
//   }

//   drawMultiple(numCards) {
//     const cards = [];
//     for (let i = 0; i < numCards; i++) {
//       cards.push(this.drawCard());
//     }
//     return cards;
//   }

//   shuffle() {
//     const { deck } = this;
//     for (let i = deck.length - 1; i > 0; i--) {
//       let j = Math.floor(Math.random() * (i + 1));
//       [deck[i], deck[j]] = [deck[j], deck[i]];
//     }
//   }
// }

// const deck1 = new Deck();
// // deck1.initializeDeck();
// // deck1.shuffle();
// const deck2 = new Deck();
// // deck2.initializeDeck();
// // deck2.shuffle();

// // deck1.drawCard();
// // deck2.drawCard();
// // deck2.drawCard();
// // deck2.drawMultiple(2);

// console.log(deck1);
// console.log(deck2);

class User {
  constructor(username, password) {
    this.username = username;
    this.password = password;
  }

  login(pass) {
    if (pass === this.password) {
      console.log('Welcome back');
    } else {
      console.log('Incorrect password entered.');
    }
  }
}

class Moderator extends User {
  constructor(username, password, age, job) {
    super(username, password);
    this.age = age;
    this.job = job;
  }

  createGroup(name) {
    console.log(`New group created: ${name}`);
  }
}

const john = new User('john123', 'doe123');
const jane = new Moderator('jane123', 'smith123', 24, 'Full Stack Dev');

john.login('doe123');
jane.login('smith123');
jane.createGroup('JavaScript');

// class User {
//   constructor(username, password) {
//     this.username = username;
//     this.password = password;
//   }

//   login(pass) {
//     if (pass === this.password) {
//       console.log('Welcome back');
//     } else {
//       console.log('Incorrect password entered.');
//     }
//   }
// }

// class Subscriber extends User {
//   logout() {
//     console.log('You have successfully logged out, Subscriber');
//   }
// }

// class Creator extends User {
//   constructor(username, password, totalVideos = 0) {
//     super(username, password);
//     this.totalVideos = totalVideos;
//   }
//   uploadVideo(videoName) {
//     this.totalVideos++;
//     console.log(
//       `Thank you for uploading ${videoName}.\nChannel: ${this.totalVideos} video(s)`
//     );
//   }

//   logout() {
//     console.log('You have successfully logged out, Creator');
//   }
// }

// const user1 = new Subscriber('johndoe', 'doe123');
// const user2 = new Creator('janedoe', 'jane123');

// user1.login('doe123');
// user2.login('asdasd');
// user2.uploadVideo('New Song');

// console.log(user1);
// console.log(user2);

Node Scratchpad

// const http = require('http');

// const server = http.createServer((request, response) => {
//   // console.log(request.url, request.method, request.headers);

//   if (request.url === '/') {
//     response.setHeader('Content-Type', 'text/html');
//     response.write(`<html>
//     <head><title>My Response</title></head>
//     <body><h1>My Response</h1></body>
//   </html>`);
//     response.end();
//   }

//   if (request.url === '/login') {
//     response.setHeader('Content-Type', 'text/html');
//     response.write(`<html>
//     <head><title>Login Page</title></head>
//     <body><h1>Try to login</h1></body>
//   </html>`);
//     response.end();
//   }
// });

// server.listen(3000);

const http = require('http');
const fs = require('fs');

const server = http.createServer((request, response) => {
  // console.log(request.url, request.method, request.headers);

  if (request.url === '/') {
    response.setHeader('Content-Type', 'text/html');
    response.write(`<html>
      <head><title>Enter Message</title></head>
      <body>
        <form action="/message" method="POST">
          <input type="text" name="message" />
          <button type="submit">Send</button>
        </form>
      </body>
    </html>`);
    return response.end();
  }

  if (request.url === '/message' && request.method === 'POST') {
    const body = [];
    request.on('data', (chunk) => {
      // console.log(chunk);
      body.push(chunk);
    });

    request.on('end', () => {
      const parsedBody = Buffer.concat(body).toString();
      const message = parsedBody.split('=')[1];
      fs.writeFileSync('message.txt', message);
    });

    // fs.writeFileSync('message.txt', 'Hello World. This is some text.');
    response.statusCode = 302;
    response.setHeader('Location', '/');
    return response.end();
  }
});

server.listen(3000);
Learn this on the racks

Reading it is one thing. Configuring it is another.

Our batches run labs like this one end to end on real kit, in the Mumbai classroom or live online, taught by practising engineers.