Full Stack Morning (12)

Full Stack Morning (12)

// let age = 21;

// if (age > 18) {
//   console.log('Entry Granted!');
// }

// console.log(1000 + 100);

// let num = 32;

// if (num % 2 !== 0) {
//   console.log('ODD');
// }

// if (num % 2 === 0) {
//   console.log('EVEN');
// }

// let num = 35;

// if (num % 2 !== 0) {
//   console.log('ODD');
// } else if (num % 2 === 0) {
//   console.log('EVEN');
// }

// let age = 67;

// if (age > 18) {
//   console.log('Entry Granted!');
// } else if (age >= 21) {
//   console.log('Drinks Allowed');
// } else if (age >= 65) {
//   console.log('Drinks FREE!');
// } else {
//   console.log('ENTRY DENIED!');
// }

// let num = 13;

// if (num % 2 !== 0) {
//   console.log('ODD');
// } else {
//   console.log('EVEN');
// }

// let age = 20;

// if (age > 18) {
//   if (age >= 65) {
//     console.log('Drinks FREE!');
//   } else if (age >= 21) {
//     console.log('Drinks Allowed');
//   } else {
//     console.log('Entry Granted!');
//   }
// } else {
//   console.log('NO ENTRY');
// }

// let isLoggedIn;

// // let name = -45;

// if (isLoggedIn) {
//   console.log('Hello!');
// } else {
//   console.log('Please login');
// }

// let loggedInUser = 10;

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

let age = 100;
let city = 'delhi';

if (age >= 18 && age < 21 && city !== 'delhi') {
  console.log('Entry Granted!');
} else if (age >= 21 && age < 65 && city !== 'delhi') {
  console.log('Drinks Allowed');
} else if (age >= 65 && city !== 'delhi') {
  console.log('Drinks FREE!');
} else {
  console.log('ENTRY DENIED!');
}

if (city === 'delhi') {
  console.log('ENTRY DENIED!');
} else if (age >= 18 && age < 21) {
  console.log('Entry Granted!');
} else if (age >= 21 && age < 65) {
  console.log('Drinks Allowed');
} else if (age >= 65) {
  console.log('Drinks FREE!');
} else {
  console.log('ENTRY DENIED!');
}
// let day = 2;

// switch (day) {
//   case 1:
//   case 2:
//   case 3:
//     console.log('HELLO WORLD');
//     break;
//   case 4:
//     console.log('THURSDAY');
//     break;
//   case 5:
//     console.log('FRIDAY');
//     break;
//   case 6:
//     console.log('SATURDAY');
//     break;
//   case 7:
//     console.log('SUNDAY');
//     break;
//   default:
//     console.log('INVALID DAY');
// }

// let num = 'nsdkjnasdlkj';

// num === 7 ? console.log('LUCKY') : console.log('UNLUCKY');

// if (num === 7) {
//   console.log('LUCKY');
// } else {
//   console.log('UNLUCKY');
// }

// let status = 'Offline'.toLowerCase();

// let color =
//   status === 'offline' ? 'red' : status === 'inactive' ? 'yellow' : 'green';

// // console.log(color);

// let status = 'inactive';
// let color;

// if (status === 'offline') {
//   color = 'red';
// } else if (status === 'inactive') {
//   color = 'yellow';
// } else {
//   color = 'green';
// }

// console.log(color);

// let s = [10 < 5]

let search = 'Predator';
const currentlyPlaying = ['Alien', 'Mad Max', 'Inception', 'Predator'];

if (currentlyPlaying.includes(search)) {
  console.log(`${search} is playing in theatres around you. Book now?`);
} else {
  console.log('Ye kya hai');
}
// const allProducts = [];

// // products (array)
// const iPhone = ['Apple iPhone 14', 200000, 'Apple', 'gold', 4, 512];
// const onePlus = [56000, 'One Plus 9', 'One Plus', 'silver', 5, 128];

// const iPhone = {
//   0: 'Apple iPhone 14',
//   1: 20000,
//   2: 'asdsad',
// };

// const iPhone = {
//   name: 'Apple iPhone 14',
//   price: 200000,
//   brand: 'Apple',
//   color: 'gold',
//   rating: 4,
//   45: 512,
//   'avg lifetime': 2,
// };

// const onePlus = {
//   storage: 128,
//   color: 'silver',
//   brand: 'One Plus',
// };

// allProducts.push(iPhone, onePlus);

// console.log(allProducts);

// iPhone[0];
// iPhone[1];
// iPhone[3];

// const users = [];

// const user1 = {
//   firstName: 'John',
//   lastName: 'Doe',
//   age: 25,
//   phone: null,
//   address: {
//     city: 'Mumbai',
//     state: 'Maharastra',
//     streetName: 'Matunga',
//   },
//   favItems: [
//     {
//       name: 'Apple iPhone 14',
//       price: 200000,
//       brand: 'Apple',
//       color: 'gold',
//       rating: 4,
//       45: 512,
//       'avg lifetime': 2,
//     },
//     {
//       storage: 128,
//       color: 'silver',
//       brand: 'One Plus',
//     },
//   ],
// };

// const pallette = {
//   red: '#eb4d4b',
//   yellow: '#f9ca24',
//   blue: '#30336b',
// };

// let color = 'green';

// console.log(pallette[color]);

// const fitnessData = {
//   totalSteps: 400000,
//   totalKms: 253.32,
//   avgCalorieBurn: 2300,
//   workoutsThisWeek: '5 of 7',
//   avgSleep: '5:45',
// }

// // Adding new property
// fitnessData.BPM = 98
// fitnessData['progress'] = 'Good'

// // Updating Properties
// fitnessData.workoutsThisWeek = '7 of 7'
// fitnessData.totalKms += 10
// fitnessData.totalSteps++

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

// for (let i = 0; i < nums.length; i++) {
//   console.log(`The value 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++) {
//   // let movie = movies[i];
//   // console.log(`Movie Name: ${movie.movieName}\nRating: ${movie.rating}`);

//   console.log(
//     `Movie Name: ${movies[i].movieName}\nRating: ${movies[i].rating}`
//   );
// }

// const word = 'Hello World';

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

// let reversedWord = '';

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

// console.log(reversedWord);

// for (let i = 1; i <= 10; i++) {
//   console.log('OUTER LOOP: ', i);

//   for (let j = 10; j >= 0; j -= 2) {
//     console.log('   INNER LOOP', j);
//   }
// }

// OUTER LOOP: 1
//    INNER LOOP: 10
//    INNER LOOP: 8
//    INNER LOOP: 6
//    INNER LOOP: 4
//    INNER LOOP: 2
//    INNER LOOP: 0
// OUTER LOOP: 2

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

let total = 0;

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

// switch (day) {
//   case 1:
//     console.log('MONDAY');
//     break;
//   case 2:
//     console.log('TUESDAY');
//     break;
//   case 'Hello World':
//     console.log('WEDNESDAY');
//     break;
//   case 4:
//     console.log('THURSDAY');
//     break;
//   case 5:
//     console.log('FRIDAY');
//     break;
//   case 6:
//     console.log('SATURDAY');
//     break;
//   case 7:
//     console.log('SUNDAY');
//     break;
//   default:
//     console.log('INVALID DAY');
// }

// let num = -1;

// num === 7 ? console.log('LUCKY') : console.log('UNLUCKY');

// for (let i = 1; i <= 10; i++) {
//   console.log('OUTER LOOP: ', i);

//   for (let j = 10; j >= 0; j -= 2) {
//     console.log('   INNER LOOP', j);
//   }
// }

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

// let j = 0;

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

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

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

// console.log(`\nGame over! \nTarget: ${target} | Guess: ${guess}`);

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

// while (guess !== target) {
//   if (guess === 13) {
//     console.log('13 is an unlucky number.\nBreaking out of this loop.');
//     break; // manually break out of the loop
//   }

//   console.log(`Target: ${target} | Guess: ${guess}`);
//   guess = Math.floor(Math.random() * 100) + 1;
// }

// console.log(`\nGame over!\nTarget: ${target} | Guess: ${guess}.`);

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

// // true -> loop forever
// while (true) {
//   console.log(`Target: ${target} | Guess: ${guess}`);

//   if (target === guess) {
//     break; // break out of the loop when condition is true
//   }

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

// console.log(`\nGame over!\nTarget: ${target} | Guess: ${guess}.`);

// let categories = [
//   'fashion',
//   'electronics',
//   'mobiles',
//   'books',
//   'toys',
//   'groceries',
// ];

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

// for (let category of categories) {
//   console.log(category);
// }

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

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

// let total = 0;

// for (let row of matrix) {
//   for (let num of row) {
//     console.log(num);
//     total += num;
//   }
// }

// console.log(total);

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

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

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

// console.log(productPrices.length);

// for (let product of Object.keys(productPrices)) {
//   console.log(`You can buy a ${product} for ${productPrices[product]}`);
// }

// const prices = Object.values(productPrices);

// let total = 0;
// for (price of prices) {
//   total = total + price;
// }
// console.log(total);

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

// let total = 0;

// for (let movie in movieRating) {
//   // console.log(movie)
//   console.log(`${movie} has a rating of ${movieRating[movie]}`);
//   total += movieRating[movie];
// }

// console.log(total);

// Named function
// function greet() {
//   console.log('Hey there!');
//   console.log('How are you?');
// }

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

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

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

// throwDice();

// // Function with a parameter
// function greet(name, age) {
//   if (typeof name === 'string' && typeof age === 'number') {
//     console.log(`How are you, ${name}. You are ${age} years old`);
//   } else {
//     console.log('Please enter values of correct types.');
//   }
// }

// greet('John', 25); // How are you, John
// greet('Jack', 27); // How are you, Jack
// greet('100', 'hello');
// greet([1, 2, 3, 4], true);

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

// // add(10, 20, '100');
// add('John', 'Doe');

// function add(b, bro) {
//   console.log(b + bro);
// }

// // add(10, 20, '100');
// add('John', 'Doe');

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

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

// throwDice(4);

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

// console.log(add(10, 15) + 100);

// function isNumber(val) {
//   if (typeof val !== 'number') {
//     return false;
//   } else {
//     return true;
//     // console.log('Hello World');
//   }
// }

// let res1 = isNumber(20);
// console.log(res1);
// let res2 = isNumber('hello');

// console.log(res1, res2);

// function greet(name, age) {
//   if (typeof name === 'string' && isNumber(age)) {
//     console.log(`How are you, ${name}. You are ${age} years old`);
//   } else {
//     console.log('Please enter values of correct types.');
//   }
// }

// greet('John Doe', 25);

let chars = 'abcdefghijklmnopqrstuvwxyz';
let i = 0;
for (let char of chars) {
  console.log(i, char);
  i++;
}
// // definition
// function add(a, b) {
//   return a + b;
// }

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

// let fullName = 'John Doe';

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

// function ungreet() {
//   let fullName = 'Jane Ma';
//   console.log(fullName);
// }

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

// greet();
// ungreet();
// console.log(fullName);

// let first_name = 'Jack';
// let last_name = 'Ma';

// if (true) {
//   var first_name = 'John';
//   var last_name = 'Doe';
//   console.log(first_name + ' ' + last_name);
// }

// console.log(first_name + ' ' + last_name);

// var i = 0;

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

// for (; i < 100; i++) {
//   console.log(i);
// }

// console.log(i);

// console.log(i + 100);

// function ungreet() {
//   var fullName = 'Jane Ma';
//   console.log(fullName);
// }

// ungreet();

// console.log(fullName);

// function outer(movie) {
//   // let movie = 'Avengers';

//   // nested function
//   function inner() {
//     // let movie = 'Robot';
//     let ratings = `${movie} has a rating of 3`;
//     console.log(ratings);
//   }

//   // console.log(ratings);

//   inner();
// }

// outer('Krish');

// // function expression or anonymous function
// const square = function (num) {
//   return num * num;
// };

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

// const myArr = [
//   function (num) {
//     return num * num * num;
//   },
//   function (num) {
//     return num * num;
//   },
// ];

// console.log(myArr[0](40));
// console.log(myArr[1](40));

// const product = function (x, y) {
//   return x * y;
// };

// console.log(product(45, 68));

// function add(x, y) {
//   return x + y;
// }

// const sub = function (x, y) {
//   return x - y;
// };

// const mul = function (x, y) {
//   return x * y;
// };

// function div(x, y) {
//   return x / y;
// }

// console.log(add, sub, mul, div(10, 2));

// const operations = [add, sub, mul, div];

// console.log(operations[0]); // [Function: add]
// console.log(operations[0](10, 23));
// console.log(operations[2](10, 4));

// for (let op of operations) {
//   let result = op(10, 2);
//   console.log(result);
// }

// const operations = {
//   add: function (a, b) {
//     return a + b;
//   },
//   sub: function (a, b) {
//     return a - b;
//   },
//   multipy: mul,
// };

// console.log(operations.add(10, 20));
// console.log(operations.sub(10, 20));
// // console.log(operations.multipy(10, 20));

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

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

// // multipleGreets(sayHello);

// multipleGreets(function () {
//   console.log('GOODBYE!');
// }, sayHello);

// 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(num) {
  return function (x) {
    return x ** num;
  };
}

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

console.log(square(2));
console.log(cube(2));
console.log(tesseract(2));
// function multipleGreets(fn) {
//   fn();
//   fn();
//   fn();
// }

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

// multipleGreets(sayHello);

// // const myFn = function () {
// //   console.log('Good bye');
// // }
// // myFn()

// multipleGreets(function () {
//   console.log('Good bye');
// });

// console.log('Starting...');

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

// setTimeout(logHello, 2000);

// setTimeout(function () {
//   let num1 = 10;
//   let num2 = 20;
//   console.log(num1 + num2);
// }, 5000);

// console.log('Finished');

// var person = 'John';

// console.log(person);
// console.log(age);
// console.log(job);

// var person = 'John';
// var age = 25;
// var job = 'Programmer';

// let person = 'John';
// let age = 25;
// let job = 'Programmer';

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

// console.log(nums.length);

// nums.forEach(function (n) {
//   console.log(`${n} time gaali`);
//   console.log(n * n);
// });

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

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

// 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());
// });

// for (let movie of movies) {
//   console.log(movie.title.toLowerCase());
// }

// movies.forEach(function (movie, idx) {
//   console.log(idx, movie.title);
// });

// const moviesUppercase = [];

// // for (let movie of movies) {
// //   moviesUppercase.push(movie.title.toUpperCase());
// //   // console.log(movie.title.toLowerCase());
// // }

// movies.forEach(function (movie) {
//   moviesUppercase.push(movie.title.toUpperCase());
// });

// console.log(moviesUppercase);

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

// const namesCapped = names.map(function (name) {
//   // console.log(name.toUpperCase());
//   return name.toUpperCase();
// });

// console.log(namesCapped);
// // ['JOHN', 'JACK', 'JANE', 'JAMES']

// const moviesUppercase = [];

// for (let movie of movies) {
//   moviesUppercase.push(movie.title.toUpperCase());
// }

// movies.forEach(function (movie) {
//   moviesUppercase.push(movie.title.toUpperCase());
// });

// const moviesUppercase = movies.map(function (movie) {
//   return movie.title.toUpperCase();
// });

// console.log(moviesUppercase);

// 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);

// ----------------------

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

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

// // // arrow function
// // const square = x => {
// //   return x * x;
// // };

// // const square = () => {
// //   return 'Hello';
// // };

// const sq = x => x * x

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

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

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

// console.log(doubles);

// 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 triples = nums.map(x => x ** 3)

// console.log(doubles)
// console.log(triples)

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

// const doubles3 = nums.map((n) => n * 2);

const parityList = nums.map(n => (n % 2 === 0 ? 'Even' : 'Odd'));

const parityList = [];
for (let n of nums) {
  if (n % 2 === 0) {
    parityList.push('Even');
  } else {
    parityList.push('Odd');
  }
}

console.log(parityList);
// let movies = ['The Terminator', 'The Avengers', 'Jurassic Park', 'Titanic'];

// let movie1 = movies.find((movie) => {
//   return movie.includes('Avenge');
// });

// let movie2 = movies.find((movie) => movie.includes('Park'));

// let movie3 = movies.find((m) => m.indexOf('A') === 0);

// console.log(movie1);
// console.log(movie2);
// console.log(movie3);

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,
  },
  {
    title: 'Two States',
    author: 'Chetan Bhagat',
    rating: 5,
  },
];

// const goodBook = books.find((book) => book.rating >= 4.3);

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

// console.log(goodBook);
// console.log(books.find((b) => b.author.includes('George')));
// console.log(lowRated);

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

// books.find((book) => book.rating < 4)

// const nums = [9, 8, 3, 4, 6, 12, 17, 23, 0];

// const odds = nums.filter((n) => n % 2 === 1);

// const odds = nums.filter((n) => n === 0);
// const odds = nums.find((n) => n === 0);

// const odd = nums.find((n) => n % 2 === 1);

// console.log(odds);
// console.log(odd);

// const bigNums = nums.filter((n) => n > 10);
// console.log(bigNums);

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

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

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

// console.log(goodBooks);
// console.log(georgeBooks);
// console.log(lowRated);

// let query = 'Alch';

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

// console.log(filteredBooks);

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

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

// console.log(names.every((word) => word.length > 3));

// let result = names.every((w) => {
//   let lastChar = w[w.length - 1];
//   return lastChar !== 'a';
// });

// console.log(result);

// const bestBooks = books.every((book) => book.rating >= 3);

// console.log(bestBooks);

// const notAuthor = books.every(
//   (book) => book.author.toLowerCase() !== 'chetan bhagat'
// );

// console.log(notAuthor);

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

// const res = names.some((word) => {
//   return word[0] === 'b';
// });

// console.log(res);

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

// // console.log(prices.sort());

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

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

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

// console.log(books);

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

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

// console.log(res);

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

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

// console.log(maxVal);

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

// console.log(maxVal);

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

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

// console.log(res);

// const multiply = (x = 1, y = 1) => {
//   return x * y;
// };

// const multiply = (x, y) => {
//   if (typeof y === 'undefined') {
//     y = 1;
//   }
//   y = typeof y === 'undefined' ? 1 : y;

//   return x * y;
// };

// console.log(multiply(8, 5));

const greet = (name = 'Ukn', msg) => {
  console.log(`${msg}, ${name}`);
};

// greet('John', 'Hey'); // "Hey John"
// greet(); // "Hi Ukn"
greet('hello'); // "Hi John"
let age = 99;

let welcome = age < 18 ? () => console.log('Baby') : () => console.log('Adult');

welcome();

Scratchpad #12

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

// const names = ['john', 'jack', 'jane', 'brad', 'tom', 45, true, 'gaali'];
// const name = 'john';

// // printVals(names);

// // printVals(['john', 'jack', 'jane'], undefined, undefined);

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

// // printVals('john', 'jack', 'jane');

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

// printVals(...name);

// const moderator = { canEdit: true, authority: 5 };
// const user = { canView: true, authority: 2.5 };

// const admin = { ...moderator, access: 'GROUP' };

// function add(x, y) {
//   return x + y;
// }

// console.log(add(10, 45, 50));

// console.log(Math.max(10, 45, 32, 67, 4, 4500));

// const addAll = (...nums) => nums.reduce((acc, curr) => acc + curr);

// console.log(addAll(10, 45, 32, 67, 89, 100, 200));

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

// printNames('john', 'jane', 'jack', 'josh', 'james', 'jamie');

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

// const firstName = user.firstName;
// const lastName = user.lastName;
// const emailAddress = user.email;

// const { firstName, lastName, email: emailAddress } = user;
// console.log(firstName, lastName, emailAddress);

// const firstName = user.firstName;

// const { firstName, lastName, emailAddress, phone } = user;
// const { firstName, lastName, email, phone } = user;

// console.log(firstName, lastName, email);

// const { firstName, lastName, ...others } = user;

// console.log(firstName, lastName, others);

// console.log(others);

// const fullName = ({ firstName: first, lastName: last }) => {
//   return `${first} ${last}`;
// };

// const fullName = ({ firstName, lastName }) => {
//   return `${firstName} ${lastName}`;
// };

// // const fullName = (obj) => {
// //   return `${obj.firstName} ${obj.lastName}`;
// // };

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

// console.log(fullName({ firstName: 'Jane', lastName: 'Doe' }));

// 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;

// console.log(highest);
// console.log(lowest);
// console.log(average);

// const info = {
//   highest: highest,
//   lowest: lowest,
//   average: average,
// };

// const info = {
//   highest,
//   lowest,
//   averageRating: average,
// };

// const info = { highest, lowest, average };

// console.log(info);

// 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 res = getReviewDetails([4.5, 5.0, 3.2, 2.1, 4.7, 3.8, 3.1, 3.9, 4.4]);

// console.log(res);

function printVals(a, b, c) {
  console.log(a);
  console.log(b);
  console.log(c);
}
const names = ['john', 'jack', 'jane'];
const name = 'john';

// printVals(names); // incorrect behaviour
// printVals(...names); // works!
printVals(...name);

Scratchpad #13

// let fullName = 'John Doe';
// let role = 'Moderator';
// let label = 'age';
// let info = ['age', 25];

// const user = {
//   firstName: fullName.split(' ')[0],
//   lastName: fullName.split(' ')[1],
//   role: role.toUpperCase(),
//   [label]: info[1],
//   [info[1] * 100]: 'Test Value',
// };

// console.log(user);

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

// const res = addProperty({ name: 'John' }, 'age', 25);

// console.log(res);

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

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

// const math = {
//   PI: 3.14,
//   multiply: (x, y) => x * y, // method
//   divide: (x, y) => x / y, // method
//   subtract: (x, y) => x - y, // method
//   square,
// };

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

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

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

// console.log(console);
// console.log(Math);

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

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

// function sayHello() {
//   console.log('Hello World!');
//   // console.log(this.closed);
//   // console.log(window.closed);
//   function greet() {
//     console.log(this);
//   }
//   greet();
// }

// sayHello();

// const helloWorld = 'Hello World !!!!!';

// sayHello();

// window.sayHello();

// console.log(window.helloWorld);

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

// const math = {
//   PI: 3.14,
//   multiply(x, y) {
//     console.log(this.PI);
//     return x * y;
//   },
//   divide(x, y) {
//     return x * y;
//   },
//   subtract(x, y) {
//     return x * y;
//   },
// };

// function logThis() {
//   console.log(this);
// }

// user.fullName();

// math.multiply(10, 34);

// logThis();

// const firstName = "Jack"

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

// user.fullName();

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

// user.fullName();

// user.firstName = 'Jack';

// user.fullName();

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

// const logDetails = user.logDetails;

// user.logDetails();
// logDetails();

// user.logDetails();

// const square = user.square;
// console.log(square(5));

// const logDetails = user.logDetails;
// console.log(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];
//   },
//   begin: () => `Hello ${this.pickMsg()}`,
//   begin2() {
//     return `Hello ${this.pickMsg()}`;
//   },
//   start() {
//     setInterval(() => {
//       console.log(this.pickMsg());
//     }, 1000);
//   },
// };

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

// hellos.start();
// console.log(hellos.begin2());
// console.log('\n\n\n');
// console.log(hellos.begin());

// const products = [
//   { title: 'hello world', price: 99 },
//   { title: 'console log this', price: 99 },
//   { title: 'hello universe', price: 99 },
//   { title: 'start this product', price: 99 },
// ];

// const findProducts = (searchTerm) => {
//   return products.filter((prod) => prod.title.includes(searchTerm));
// };
// let res = findProducts('hello');
// console.log(res);

// let USD = 75;
// const productsINR = products.map((prod) => prod.price * USD);

//Exercise 6;

// const productINR = products.map((prod) => ({
//   id: prod.id,
//   title: prod.title,
//   description: prod.description,
//   category: prod.category,
//   image: prod.image,
//   price: prod.price * 75,
// }));

const productINR = products.map((prod) => ({
  ...prod,
  price: prod.price * 75,
}));

console.log(productINR);
// console.log('Hello world');

// const pageTitle = document.getElementById('mainTitle');
// const paras = document.getElementsByTagName('p');
// const imgs = document.getElementsByTagName('img');

// // console.dir(pageTitle);
// // console.dir(paras);

// // for (let p of paras) {
// //   console.log(p.outerHTML);
// // }

// console.dir(imgs);

// const myImage = document.getElementById('impImg');
// // console.dir(myImage);

// const specialEls = document.getElementsByClassName('special');
// // console.dir(specialEls[1]);

// const specialLists = document.getElementsByClassName('special-list');
// // console.dir(specialLists[0]);

// // console.log(document.getElementsByClassName('special'));

// const pageTitle = document.querySelector('#mainTitle');
// const pageLists = document.querySelector('.special');
// const unordered = document.querySelectorAll('ul > li');
// const title = document.querySelectorAll('h1');

// console.log(pageTitle);
// console.log(pageLists);
// console.log(unordered);
// console.log(title);

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

// console.log(h1.innerText);
// h1.innerText = 'RST FORUM';

// console.log(document.body.innerText);

// const img = document.querySelector('img');
// // document.body.innerText = 'HELLO WORLD';
// img.innerText = 'HI!';

// const ul = document.querySelector('ul');
// ul.innerText = 'CHANGED all of this';
// // console.log(ul);

// const h1 = document.querySelector('h1');
// console.log(h1.textContent);

// const para = document.querySelector('.special2');
// console.log(para.textContent);

// const myPara = document.querySelector('.my-para'); // object

// console.log(myPara.innerHTML);

// // myPara.innerText = '<strong>Hello</strong> this has been modified';
// myPara.innerHTML =
//   '<strong style="color: red">Hello</strong> this has been modified';

// myPara.innerHTML += '. <em>Extra information.</em>';

// const inputs = document.querySelectorAll('input');
// inputs[0].value = 'John';
// inputs[1].value = 'Doe';

const img = document.querySelector('img');
// img.src =
//   'file:///C:/Users/rahul.LAPTOP-IB8N85JR/Desktop/Training/Full_Stack_15/HTML-CSS/js/images/car.jpg';
// // console.log(img.src);

// // console.log(img.width);

// img.width = '300';

// const range = document.querySelector('input[type="range"]');
// // console.log(img.getAttribute('alt'));
// // console.log(range.getAttribute('max'));

// console.log(img.getAttribute('src'));
// console.log(img.src);
// console.log(img.getAttribute('width'));

// img.setAttribute('alt', 'Text added via JS');
// img.setAttribute('width', '50%');

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

// btn.setAttribute('type', 'button');
// btn.setAttribute('style', 'border: 2px solid red');
// const multiply2 = (x = 1, y = 1) => {
//   return x * y;
// };

// multiply(10);

// function addAll2(...nums) { // rest args
//   console.log(nums)
//   let total = 0
//   nums.forEach(num => (total += num))
//   return total
// }

// const fullName = (user) => {
//   return `${user.firstName} ${user.lastName}`
// }

// fullName({firstName: 'John', lastName: 'Doe'})

// const fullName = ({ firstName, lastName }) => {
//   return `${firstName} ${lastName}`
// }

// 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: highest, lowest: lowest, average: average };
// console.log(info1);

// function multiply(x, y) {
//   return x * y
// }

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

// const math2 = {
//   multiply(x, y) {
//     return x * y
//   }
// }

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

// greet();

// const window = {
//   greet() {
//     console.log('Hello World!');
//     console.log(this);
//   }
// }

// greet()
// window.greet()

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

// // console.log(firstLi.parentElement.parentElement);

// const allLis = ul.children;
// const form = document.querySelector('form');

// // console.log(ul.children);

// // for (let li of allLis) {
// //   console.log(li.innerText);
// // }

// // console.log(form.children[0].innerHTML);

// // console.log(form.nextElementSibling);
// console.log(form.previousElementSibling);

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

// for (li of lis) {
//   // console.log(li.innerText)
//   // li.innerText = 'Programmatically CHANGED!'
//   li.innerHTML = 'Programmatically <b>CHANGED!</b>';
// }

// const heading = document.querySelector('h1');

// // console.log(heading.style);

// heading.style.color = 'red';
// heading.style.textDecoration = 'underline';
// heading.style.fontSize = '50px';

// const lis = document.querySelectorAll('li');
// const colors = ['red', 'yellow', 'green', 'orange', 'teal'];

// for (li of lis) {
//   li.style.color = colors[Math.floor(Math.random() * colors.length)];
//   li.style.fontSize = '20';
//   li.style.fontWeight = 'bold';
//   li.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
//   li.style.fontFamily = 'Helvetica, sans-serif';
// }

// const para = document.querySelector('.styled-el');

// // console.log(para.style);
// const paraStyles = getComputedStyle(para);

// // console.log(paraStyles);

// console.log(paraStyles.textDecoration);
// console.log(paraStyles.color);
// console.log(paraStyles.fontSize);

// para.style.color = 'green';

// console.log(paraStyles.color);

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

// console.log(todo);

// todo.style.textDecoration = 'line-through';
// todo.style.opacity = 0.5;
// todo.style.color = 'red';

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

// console.log(todo.classList);

// todo.classList.add('done');
// todo.classList.remove('done');

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

// const subtitle = document.createElement('h2');

// subtitle.innerText = 'This is a subtitle';
// subtitle.style.fontSize = '35px';

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

// // section.appendChild(subtitle);

// const photo = document.createElement('img');
// photo.setAttribute(
//   'src',
//   'https://images.unsplash.com/photo-1619448532901-bdfa33279554?ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwxfHx8ZW58MHx8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=600&q=60'
// );
// photo.style.width = '400px';

// const photoLink = document.createElement('a');
// photoLink.setAttribute(
//   'href',
//   'https://images.unsplash.com/photo-1619448532901-bdfa33279554?ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwxfHx8ZW58MHx8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=600&q=60'
// );
// photoLink.setAttribute('target', '_blank');

// photoLink.appendChild(photo);

// section.appendChild(photoLink);

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

// const newTask = document.createElement('li');

// newTask.innerText = 'Brand new task to complete';
// // newTask.innerHTML = 'Brand new task to complete <button>X</button>'
// newTask.classList.add('todo');
// newTask.style.color = 'purple';
// newTask.style.fontWeight = 'bold';

// // todos.appendChild(newTask); // append to the end

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

// // console.log(firstTask);

// todos.insertBefore(newTask, firstTask);

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

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

// // p.insertAdjacentElement('beforebegin', b);
// // p.insertAdjacentElement('afterbegin', b);
// // p.insertAdjacentElement('beforeend', b);
// 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.append(b, i); // append both b and i to the end of p
// // p.append(b); // just append b to the end of p
// p.prepend(i); // prepend i to the start of p

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

// const firstTask = todos.querySelector('li');
// console.log(firstTask);

// const secondTask = firstTask.nextElementSibling;
// console.log(secondTask);

// // todos.removeChild(firstTask);
// // todos.removeChild(secondTask);

// // firstTask.remove();
// // secondTask.remove();

// const btn = document.querySelector('#btn1');

// btn.onclick = () => console.log('I GOT CLICKED');
// btn.onclick = () => console.log('Click second event');

// btn.addEventListener('click', () => {
//   alert('ALERT MESSAGE FROM CLICK EVENT');
// });

// btn.addEventListener('click', () => {
//   console.log('CONSOLE MESSAGE FROM CLICK EVENT');
// });

// btn.addEventListener('mouseover', () => {
//   console.log('I have been hovered upon');
// });

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

// btn.addEventListener('mouseout', function () {
//   btn.innerText = 'Button 1';
// });

// // Attach a scroll event on the window itself
// window.addEventListener('scroll', function () {
//   console.log('Stop Scrolling!');
// });

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

// btn.addEventListener('mouseover', function () {
//   // console.log('Mouse over button')
//   // To get the current height and width of your browser screen
//   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 printColor = function (box) {
//   console.log(box.style.backgroundColor);
// };

// We can make use of `this`
const printColor = function () {
  console.log(this.style.backgroundColor);
};

const changeColor = function () {
  const h1 = document.querySelector('h1');
  h1.style.color = this.style.backgroundColor;
  h1.innerText = this.style.backgroundColor + ' selected';
};

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

// 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', function () {
  //   // console.log('Box clicked!')
  //   // console.log(box.style.backgroundColor);
  //   printColor(box);
  // });

  box.addEventListener('click', printColor);
  box.addEventListener('click', changeColor);
}
// const colors = [
//   'red',
//   'orange',
//   'yellow',
//   'green',
//   'blue',
//   'purple',
//   'indigo',
//   'violet',
// ];

// const printColor = function (event) {
//   console.log(this.style.backgroundColor);
// };

// const changeColor = function (event) {
//   console.log(event);
//   const h1 = document.querySelector('h1');
//   h1.style.color = this.style.backgroundColor;
//   h1.innerText = this.style.backgroundColor + ' selected';
// };

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

// // 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

//   box.addEventListener('click', printColor);
//   box.addEventListener('click', changeColor);
// }

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

// // input.addEventListener('keydown', function (e) {
// //   console.log('KEY DOWN', e);
// // });

// // input.addEventListener('keyup', function (e) {
// //   console.log('KEY UP', e);
// // });

// input.addEventListener('keypress', function (e) {
//   console.log('KEY PRESS', e);
// });

// const taskAdd = document.querySelector('#addtask');
// const todos = document.querySelector('#todos');
// const output = document.querySelector('#output');

// // let val = '';

// taskAdd.addEventListener('keypress', function (e) {
//   // console.log(e.key);
//   // console.dir(this);
//   // val = e.target.value;
//   // this.value = val;

//   output.innerText = e.target.value;

//   if (e.key === 'Enter') {
//     if (!this.value) {
//       return;
//     }
//     const newTask = document.createElement('li');
//     newTask.innerText = this.value;
//     newTask.style.cursor = 'pointer';

//     todos.append(newTask);
//     this.value = '';

//     newTask.addEventListener('click', function () {
//       newTask.remove();
//     });
//   }
// });

// const form = document.querySelector('#payment-form');

// const creditCard = document.querySelector('#cc');
// const terms = document.querySelector('#terms');
// const brand = document.querySelector('#brand');

// form.addEventListener('submit', function (e) {
//   // alert('FORM SUBMITTED');
//   e.preventDefault(); // prevent the default form behavior

//   console.log('cc - ', creditCard.value);
//   console.log('terms - ', terms.checked);
//   console.log('brand - ', brand.value);
// });

// const formData = {};

// creditCard.addEventListener('input', function (e) {
//   // console.log('CC changed', e);
//   formData['cc'] = e.target.value;
//   console.log(e.target.value);
// });

// brand.addEventListener('input', function (e) {
//   // console.log('brand changed', e);
//   formData['brand'] = e.target.value;
//   console.log(e.target.value);
// });

// terms.addEventListener('input', function (e) {
//   // console.log('terms changed', e);
//   formData['terms'] = e.target.checked;
//   console.log(e.target.checked);
// });

// const form = document.querySelector('#payment-form');

// const creditCard = document.querySelector('#cc');
// const terms = document.querySelector('#terms');
// const brand = document.querySelector('#brand');

// const formData = {};

// for (let input of [creditCard, terms, brand]) {
//   input.addEventListener('input', (e) => {
//     formData[e.target.name] =
//       e.target.type === 'checkbox' ? e.target.checked : e.target.value;
//   });
// }

// form.addEventListener('submit', function (e) {
//   // alert('FORM SUBMITTED');
//   e.preventDefault(); // prevent the default form behavior
//   console.log(formData);
// });

// 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');

// const moveX = (element, amount, delay, callback) => {
//   setTimeout(() => {
//     element.style.transform = `translateX(${amount}px)`;
//     if (callback) {
//       callback();
//     }
//   }, delay);
// };

// moveX(btn, 100, 1000, () => {
//   moveX(btn, 200, 1000, () => {
//     moveX(btn, 300, 1000, () => {
//       moveX(btn, 400, 1000, () => {
//         moveX(btn, 500, 1000, () => {
//           moveX(btn, 500, 1000, () => {
//             moveX(btn, 500, 1000);
//           });
//         });
//       });
//     });
//   });
// });

// 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)`;
//         }, 1000);
//       }, 1000);
//     }, 1000);
//   }, 1000);
// }, 1000);

// const subtitle = document.createElement('h2');
// subtitle.innerText = 'This is a subtitle';
// subtitle.style.fontSize = '35px';

// const section = document.querySelector('section');
// section.appendChild(subtitle);

// const photo = document.createElement('img');
// photo.setAttribute(
//   'src',
//   'https://images.unsplash.com/photo-1619448532901-bdfa33279554?ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwxfHx8ZW58MHx8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=600&q=60'
// );
// photo.style.width = '400px';

// const photoLink = document.createElement('a');
// photoLink.setAttribute(
//   'href',
//   'https://images.unsplash.com/photo-1619448532901-bdfa33279554?ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwxfHx8ZW58MHx8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=600&q=60'
// );
// photoLink.setAttribute('target', '_blank');

// photoLink.appendChild(photo);
// section.appendChild(photoLink);

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

// const newTask = document.createElement('li');
// newTask.innerText = 'Brand new task to complete';
// // newTask.innerHTML = 'Brand new task to complete <button>X</button>'
// newTask.classList.add('todo');
// newTask.style.color = 'purple';
// newTask.style.fontWeight = 'bold';

// // todos.appendChild(newTask); // append to the end

// const firstTask = todos.querySelector('li');
// todos.insertBefore(newTask, firstTask); // insert before a certain element

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

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

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

// p.insertAdjacentElement('afterbegin', b);
// p.insertAdjacentElement('beforeend', b);
// 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.append(b, i); // append both b and i to the end of p
// // // p.append(b); // just append b to the end of p
// // p.prepend(i); // prepend i to the start of p

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

// const firstTask = todos.querySelector('li');
// // console.log(firstTask);
// const secondTask = firstTask.nextElementSibling;
// // console.log(secondTask);

// todos.removeChild(firstTask);
// todos.removeChild(secondTask);

// firstTask.remove();
// secondTask.remove();

// const btn = document.querySelector('button');
// // btn.onclick = console.log('Incorrect EVENT');

// btn.onclick = function () {
//   console.log('Click first event');
//   return 'hello';
// };

// btn.onclick = function () {
//   console.log('Click second event');
// };

// const btn = {
//   hello: 'hello',
//   onclick: function () {
//     console.log('Click second event');
//   },
// };

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

// // it takes a callback
// btn.addEventListener('click', () => {
//   // alert('ALERT MESSAGE FROM CLICK EVENT');
//   console.log('CONSOLE MESSAGE FROM');
// });

// // can add as many events as you want
// btn.addEventListener('click', () => {
//   console.log('CONSOLE MESSAGE FROM CLICK EVENT');
// });

// // can add as many events as you want
// btn.addEventListener('mouseover', () => {
//   console.log('CONSOLE MESSAGE FROM CLICK EVENT');
// });

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

// btn.addEventListener('mouseout', function () {
//   btn.innerText = 'Button 1';
// });

// window.addEventListener('scroll', function () {
//   console.log('Stop Scrolling!');
// });

// 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

// // 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', function () {
//     // console.log('Box clicked!')
//     console.log(box.style.backgroundColor);
//   });
// }

const printColor = function () {
  console.log(this.style.backgroundColor);
};

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);
}
// moveX(btn, 100, 1000, () => {
//   moveX(btn, 200, 1000, () => {
//     moveX(btn, 300, 1000, () => {
//       moveX(btn, 400, 1000, () => {
//         moveX(btn, 500, 1000, () => {
//           moveX(btn, 500, 1000, () => {
//             moveX(btn, 500, 1000);
//           });
//         });
//       });
//     });
//   });
// });

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

//   if (rand < 0.5) {
//     resolve();
//   } else {
//     reject();
//   }
// });

// // console.log(willGetAPlayStation);

// willGetAPlayStation.then(() => console.log('I got a playstation. Thank you.'));
// willGetAPlayStation.catch(() => console.log('Mai ghar chod dunga'));

// 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 });
//       }
//     }, 2000);
//   });
// };

// // const result = fakeRequest('/users');

// // result
// //   .then((response) => console.log(response))
// //   .catch((response) => console.log(response));

// fakeRequest('/users')
//   .then((res) => console.log(res.status, res.data))
//   .catch((res) => console.log(res.status));

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/4': {
          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(res);
//     const id = res.data[0].id;

//     fakeRequest(`/users/${id}`).then((res) => {
//       console.log(res);
//       const postId = res.data.topPostId;

//       fakeRequest(`/posts/${postId}`).then((res) => {
//         console.log(res);
//       });
//     });
//   })
//   .catch((err) => console.log(err));

fakeRequest('/users')
  .then((res) => {
    const id = res.data[0].id;
    return fakeRequest(`/users/${id}`);
  })
  .then((res) => {
    const postId = res.data.topPostId;
    return fakeRequest(`/posts/${postId}`);
  })
  .then((res) => {
    console.log(res);
  })
  .catch((err) => console.log(err));
// const req = new XMLHttpRequest(); // make new object

// // // provide 2 callbacks

// req.onload = function () {
//   // if successful
//   console.log('SUCCESS!');
//   const data = JSON.parse(this.responseText);
//   console.log(data);
// };

// req.onerror = function (err) {
//   // if failure
//   console.log('ERROR', err);
// };

// req.open('get', 'https://swapi.dev/api/people/1', true); // request type and url

// req.setRequestHeader('Accept', 'application/json'); // send headers

// req.send(); // send request

// // Event listeners
// const req = new XMLHttpRequest();

// // Adding event listeners instead of attributes
// req.addEventListener('load', function () {
//   const data = JSON.parse(this.responseText);

//   // console.log('It worked!', data);

//   for (let planet of data.results) {
//     console.log(planet.name);
//   }
// });

// req.addEventListener('error', function (err) {
//   console.log('Error', err);
// });

// req.open('get', 'https://swapi.dev/api/planets', true);
// req.send();

// console.log(req); // req object has the responseText field

// const req = new XMLHttpRequest();

// req.addEventListener('load', function () {
//   console.log('First Request');
//   const data = JSON.parse(this.responseText);

//   const filmUrl = data.results[0].films[0];

//   ///////////////////////// SECOND REQUEST

//   // Second Request (nested)
//   const filmReq = new XMLHttpRequest();

//   filmReq.addEventListener('load', function () {
//     console.log('Second Request');
//     const filmData = JSON.parse(this.responseText);
//     console.log(filmData.title);

//     /////////////////// THIRD REQUEST
//   });

//   filmReq.addEventListener('error', function (err) {
//     console.log(err);
//   });

//   filmReq.open('GET', filmUrl, true);
//   filmReq.send();

//   //////////////////////// END SECOND REQUEST
// });

// req.addEventListener('error', function (err) {
//   console.log('Error', err);
// });

// req.open('get', 'https://swapi.dev/api/planets', true);
// req.send();

// fetch('https://swapi.dev/api/planets', {
//   headers: { Accept: 'application/json' },
// })
//   .then((response) => {
//     // console.log(response);
//     if (response.status !== 200) {
//       console.log('Problem', response.status);
//       return;
//     }

//     // // Have to use response.json as we get back a stream
//     // // and not the json directly.
//     response.json().then((data) => {
//       // itself is a promise
//       console.log(data);
//     });
//   })
//   .catch(function (err) {
//     console.log('Fetch err', err);
//   });

// fetch('https://swapi.dev/api/plannets')
//   .then((response) => {
//     if (!response.ok) {
//       // console.log('Something went wrong!', response.status);
//       throw new Error(`Status code error: ${response.status}`);
//     } else {
//       response.json().then((data) => {
//         for (let planet of data.results) {
//           console.log(planet.name);
//         }
//       });
//     }
//   })
//   .catch((err) => {
//     console.log('ERROR!', err);
//   });

// fetch('https://swapi.dev/api/plannnnnnnets')
//   .then((response) => {
//     console.log(response);
//     if (!response.ok) {
//       throw new Error(`Status code error: ${response.status}`);
//     }
//     return response.json();
//   })
//   .then((data) => {
//     console.log('Fetched all planets');
//     const filmUrl = data.results[0].films[0];
//     return fetch(filmUrl);
//   })
//   .then((response) => {
//     if (!response.ok) {
//       throw new Error(`Status code error: ${response.status}`);
//     }
//     return response.json();
//   })
//   .then((data) => {
//     console.log('Fetched first film');
//     console.log(data.title);
//   })
//   .catch((err) => {
//     console.log('ERROR!', err);
//   });

// // Custom function to extract checking and parsing logic
// const checkStatusAndParse = (res) => {
//   if (!res.ok) {
//     throw new Error(`Status code error: ${res.status}`);
//   }
//   return res.json();
// };

// fetch('https://swapi.dev/api/planets')
//   .then((response) => {
//     return checkStatusAndParse(response);
//   })
//   .then((data) => {
//     console.log('Fetched all planets');
//     const filmUrl = data.results[0].films[0];
//     return fetch(filmUrl);
//   })
//   .then((response) => {
//     return checkStatusAndParse(response);
//   })
//   .then((data) => {
//     console.log('Fetched first film');
//     console.log(data.title);
//   })
//   .catch((err) => {
//     console.log('ERROR!', err);
//   });

// // Custom function to extract checking and parsing logic
// 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) => {
//     console.log('Fetched all planets');
//     const filmUrl = data.results[0].films[0];
//     return fetch(filmUrl);
//   })
//   .then(checkStatusAndParse)
//   .then((data) => {
//     console.log('Fetched first film');
//     console.log(data.title);
//   })
//   .catch((err) => {
//     console.log('ERROR!', err);
//   });

// axios
//   .get('https://swapi.dev/api/planets')
//   .then(({ data }) =>
//     data.results.forEach((planet) => console.log(planet.name))
//   )
//   .catch((err) => console.log('In Catch Block: \n\n', err));

axios
  .get('https://swapi.dev/api/planets')
  .then(({ data }) => {
    data.results.forEach((planet) => console.log(planet.name));
    return axios.get(data.next);
  })
  .then(({ data }) =>
    data.results.forEach((planet) => console.log(planet.name))
  )
  .catch((err) => console.log('ERROR OCCURRED', err));
// function getData() {
//   const data = axios.get('https://swapi.dev/api/planets');
//   console.log(data); // Promise {<pending>}
// }

// getData();

// function getData() {
//   axios.get('https://swapi.dev/api/planets').then((res) => {
//     console.log(res); // {data: {…}, status: 200, …}
//   });
// }

// getData();

// async function greet() {
//   return 'Hello!';
// }

// console.log(greet());

// async function problem() {
//   throw new Error('Problem!');
// }

// // console.log(problem());

// // greet().then((res) => {
// //   console.log(res);
// // });

// problem().catch((res) => {
//   console.log(res);
// });

// async function add(x, y) {
//   if (typeof x !== 'number' || typeof y !== 'number') {
//     throw new Error('X and Y must be numbers');
//   }
//   return x + y;
// }

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

// add('hello', 10)
//   .then((res) => {
//     console.log(res);
//   })
//   .catch((res) => {
//     console.log(res);
//   });

// function getPlanets() {
//   return axios.get('https://swapi.dev/api/planets');
// }

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

// async function getPlanets() {
//   try {
//     const res = await axios.get('https://swapi.dev/api/planets');
//     console.log(res.data);
//   } catch (err) {
//     console.log(err);
//   } finally {
//     console.log('Hello world');
//   }
// }

// getPlanets().catch((err) => {
//   console.log('In catch block:', err);
// });

// getPlanets();

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

// async function getPokemon() {
//   const pokemon1 = await axios.get('https://pokeapi.co/api/v2/pokemon/1');
//   const pokemon2 = await axios.get('https://pokeapi.co/api/v2/pokemon/2');
//   const pokemon3 = await axios.get('https://pokeapi.co/api/v2/pokemon/3');

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

// getPokemon();

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

//   await pokemon1;
//   await pokemon2;
//   await pokemon3;

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

// getPokemon();

// async function getPokemon() {
//   // 15
//   const promise1 = axios.get('https://pokeapi.co/api/v2/pokemon/1');
//   const promise2 = axios.get('https://pokeapi.co/api/v2/pokemon/2');
//   const promise3 = axios.get('https://pokeapi.co/api/v2/pokemon/3');

//   // 5
//   const pokemon1 = await promise1;
//   const pokemon2 = await promise2;
//   const pokemon3 = await promise3;

//   console.log('Pokemon 1', pokemon1.data);
//   console.log('Pokemon 2', pokemon2.data);
//   console.log('Pokemon 3', pokemon3.data);
// }

// getPokemon();

// console.log('Pokemon 1', await promise1);
// console.log('Pokemon 2', await promise2);
// console.log('Pokemon 3', await promise3);

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

//   const results = await Promise.all([promise1, promise2, promise3]);
//   console.log(results); // array
// }

// getPokemon();

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

//   const results = await Promise.all([promise1, promise2, promise3]);
//   // console.log(results) // array
//   logPokemonToConsole(results);
// }

// function logPokemonToConsole(results) {
//   for (let pokemon of results) {
//     console.log(pokemon.data.name);
//   }
// }

// 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 myDeck = initializeDeck();
// const cardsInHand = [];

// console.log(myDeck.length);

// drawCard(myDeck, cardsInHand);
// drawCard(myDeck, cardsInHand);
// drawCard(myDeck, cardsInHand);

// console.log(myDeck.length);

// drawMultiple(5, myDeck, cardsInHand);

// console.log(cardsInHand);

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

// console.log(myDeck);

// 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--) {
//         console.log(deck);
//         let j = Math.floor(Math.random() * (i + 1));
//         [deck[i], deck[j]] = [deck[j], deck[i]];
//       }
//     },
//   };
// };

// const myDeck = makeDeck();

// myDeck.initializeDeck();
// myDeck.drawCard();
// myDeck.drawCard();
// myDeck.drawCard();
// myDeck.drawCard();

// console.log(myDeck.drawnCards);

// function makePerson(fname, lname, age) {
//   return {
//     firstName: fname,
//     lastName: lname,
//     age: age,
//     sayName() {
//       console.log(this.firstName, this.lastName);
//     },
//   };
// }

// const john = makePerson('John', 'Doe', 25);
// const jane = makePerson('Jane', 'Doe', 25);

// // john.sayName();
// // jane.sayName();

// console.log(typeof john);

// ------------------

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

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

// const jim = new Person('Jim', 'Doe', 25);
// const jack = new Person('Jack', 'Doe', 25);

// // jim.sayName();
// // jack.sayName();

// console.log(typeof jim);

// class Person {
//   constructor(firstName, lastName, age) {
//     console.log('INSIDE CONSTRUCTOR');
//     console.log(firstName, lastName, age);
//     this.firstName = firstName;
//     this.lastName = lastName;
//     this.age = age;
//   }

//   greet() {
//     console.log(`Hello friend, from ${this.firstName}`);
//   }
// }

// const person1 = new Person('John', 'Doe', 25);
// const person2 = new Person('Jane', 'Doe', 25);

// console.log(person1);

// person1.greet();

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 john = new User('john', 'john@123');
const jane = new Subscriber('jane', 'jack@123');
const jack = new Creator('jack', 'jack@987', 100);

john.login('jane@123');
jane.login('jack@123');

// console.log(john);
// console.log(jane);

jack.login('jack@987');
jack.uploadVideo('tiktok video #555');
<!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>React</title>
  </head>
  <body>
    <div id="root"></div>

    <script src="https://unpkg.com/react@^16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@^16/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>

    <script type="text/babel">
      // const rootElement = document.querySelector('#root');
      // const heading = document.createElement('h1');
      // heading.innerText = 'Hello World!';
      // rootElement.append(heading);

      // const element = React.createElement('h1', {
      //   className: 'title', // add a class to this element
      //   children: 'Hello Universe!', // the content of this h1 element
      // });

      // Nested
      // const headingEl = React.createElement(
      //   'h1',
      //   { className: 'myHeading' },
      //   'Hello World!'
      // );

      // const heading = <h1 id="title">Hello World</h1>;

      // const paraEl = React.createElement(
      //   'p',
      //   {},
      //   'I am rendered using React JS'
      // );

      // const element = React.createElement('div', {
      //   className: 'intro-div',
      //   children: [heading, paraEl], // children property can be an array
      // });

      // console.log(element);

      // const children = 'Hello World. This is the page title';
      // const className = 'title';

      // const props = { children, className };

      // // JSX tags can be self closing
      // // Below we spread the props object in the JSX element
      // const element = <h1 {...props} className="new" />;

      const message = 'Hello World';
      const myClassName = 'special';

      // Interpolated myClassName and message
      const element = <h1 className={myClassName}>{message.toUpperCase()}</h1>;

      ReactDOM.render(element, document.querySelector('#root'));
    </script>
  </body>
</html>

1. Generate some boilerplate for a basic React application.

  • Go into your workspace/projects directory using the terminal.
  • cd ~/Documents/FullStack/Workspace
  • mkdir rststore
  • npx create-react-app@latest frontend –use-npm
  • code .
  • cd frontend
  • npm start
  • Open public/index.html and clean up the file. Remove all the comments and change the title and meta content.
  • Delete all the files in the src folder. Create and add basic boilerplate code to App.js and index.js.

2. Chakra UI Installation and Setup

  • npm i @chakra-ui/react @emotion/react @emotion/styled framer-motion
  • npm install react-icons –save
  • Edit index.js file. Import ChakraProvider component and wrap the App component with it.

3. Create Header and Footer components

  • Create a folder called src/components in the src folder and add all components in that.

4. Create HomeScreen product listings

  • Create the HomeScreen component (all display/screen components will go in the /screens folder), along with the product and ratings components.

5. Install and Implement React Router

  • npm install react-router-dom
  • Complete all the React Router setup on the App page.
  • Modify Product cards, Header links etc. Use React Routers Link component instead.

6. Design and build the ProductScreen component.

7. Setting up the backend

  • Close the React server.
  • Create a folder named backend outside the frontend folder in the root of our project.
  • npm init in the root. (not inside the backend or frontend folders, but outside in the root directory)
  • During npm init setup the main will be server.js
  • npm install express (in the root folder)
  • Create a file backend/server.js in the backend folder and a folder data and copy products.js to this folder.
  • Create some routes to serve the data from the backend
  • Create a script for start in package.json
  • Create 2 basic routes for ‘/’ and ‘/api/products’
  • Convert products.js export statement to commonjs format.
  • Create another route to fetch single product by id.

8. Fetching data from our backend using React

  • Inside the frontend folder, run npm install axios
  • Modify the HomeScreen component to fetch and store data in the component.
  • To fix the issue of our backend address for now, we’ll add a proxy to the frontend’s package.json. Add this “proxy”: “http://127.0.0.1:5000”, to frontend/package.json
  • Make sure both frontend and backend are running in two terminals and test it out.
  • Modify the ProductScreen component to also make a request to our backend to fetch data.
  • Delete the projects.js file from our frontend’s src folder as we no longer need it.

9. More backend setup

  • In the root directory: run
  • npm install -D nodemon concurrently. ‘-D’ is a dev dependency, meaning we only need these modules during development.
  • These above packages will help us auto restart our server when we change our code, so we don’t have to do it manually.
  • Modify scripts in package.json (root folder) to add some scripts to use our npm command directly to work them.

10. Setup environment variables

  • npm install dotenv
  • Do the dotenv setup in server.js file and create a .env file in the root folder.

11. Convert imports to ES Modules

  • Add “type”: “module” to package.json file. Change all import and export statements to ES module style.
  • Note: You will have to add .js extension while using ES modules in the backend.

12. Install and setup MongoDB

  • After installation, setup MongoDB Compass
  • Use this as the connection string: mongodb://localhost:27017/rststore
  • Add the following in the .env
    MONGO_URI = mongodb://localhost:27017/rststore

13. Connect to the database

  • Install mongoose: npm install mongoose (in the root folder)
  • Create a folder named config in the backend folder and create a file named backend/config/db.js inside it.
  • Do all the mongoDB connection setup
  • Import db.js into server.js and run the connectDB function.
  • Start the server and check if any error.

14. Improve console log messages.

  • Run this command in the root folder: npm install colors
  • Add stylings to server and db console messages.

15. Create database models for data

  • Create a models folder inside the backend folder.
  • Create all our data model schemas.

16. Prepare sample data for the backend data seeding

  • Delete all the _id key-values from the products.js as MongoDB
    will automatically create it for us.
  • Create data/users.js file and fill it with a few user objects.
  • npm install bcryptjs – for password hashing
  • Use bcryptjs for the password fields to encrypt the password. (temporary)

17. Create database seeder for quick sample data generation (optional)

  • Create backend/seeder.js file inside the backend folder.
  • Add seeding logic and create import and destroy scripts.

18. Fetching products from the database

  • Create a folder named backend/routes in the backend folder.
  • Create a file named backend/routes/productRoutes.js
  • npm install express-async-handler – we will wrap our callbacks with this function so that we can do error handler in a better way.
  • Move the products and single product fetch routes to this file and add all the logic for now.
  • Test the routes in Postman

19. Do Postman setup to work with our API (optional)Custom error handling. Run the following in the root folder.

  • npm install express-async-handler
  • Create a folder named backend/middleware in the backend folder
  • Create an errorMiddleware.js and add logic to handle errors.

20. Introduction to Redux

  • The Redux Pattern
  • Download the Redux DevTools brower extension.
  • Go to the frontend folder. cd frontend
  • npm install redux react-redux redux-thunk redux-devtools-extension
  • In the src folder, create a file named store.js
  • Import Provider and store into the index.js and do all the setup.

21. Create our first reducer

  • In frontend/src create a folder called reducers – (frontend/src/reducers).
  • Create a file (our reducer) named productReducer.js inside the reducers folder and add all the reducer logic.
  • Next, import productListReducer to store.js and add it to the combineReducers({}) function’s argument object as a new key/value.
  • Create a folder called constants in the frontend/src folder and inside it create the productConstants.js file to store all our action names.

22. Getting Redux State in the Home Screen

  1. Clean up the file. Remove axios import, the [products, setProducts] state variables and remove everything from inside useEffect. We don’t need these anymore.
  2. Import useDispatch and useSelector from ‘react-redux’. Also import listProducts from ‘../actions/productActions’.
  3. The first hook will be used to dispatch/call an action, and the other is use to select parts of the state. Here we will need the productList part of the state.

23. Getting Redux State in the Home Screen

  • Create the dispatch object using the useDispatch hook and call it in useEffect to
    fire the listProducts action.
  • To select products from our state, we need to use the useSelector hook. This hook will take in an arrow function. This function gets state and then we can select which part of the state do we want.
  • Add a conditional to display a loading messageerror message or our product list.

24. Create Message and Loader components.

  • Use the Spinner and Alert components from ChakraUI to add these.

25. Single product details screen Reducer and Action

  • Again, we will follow the same pattern/steps as earlier.
  • Start off by adding the required constants. Since this is for the single product screen, we will add the constants once again to the productConstants.js
  • Create a new reducer named productDetailsReducer in productReducers.js.
  • Whenever we create a new reducer, we have to add it to our store. So, import productDetailsReducer in the store.js file and add a new piece of state named productDetails.
  • Next, step will be to create an action. Add a new action named listProductDetails to the actions file.
  • Next, in the ProductScreen.js, get rid of axios and clean up useEffect. Import useDispatchuseSelector and the listProductDetails action that we just created.
  • Create the dispatch object and dispatch the listProductDetails action in the useEffect hook. You will now be able to see the state in Redux Devtools.
  • Use useSelector hook and select the productDetails piece of state. De-structure the correct values and use them in the JSX to display the product details, error and loading components.

26. Cart and Quantity

  • Add a quantity select box with it’s logic to only contain the number of items in stock.
  • The add to cart button should redirect to the a cart page/screen with the product id and quantity as a query string.

27. Cart Screen and Route

  • Create screens/CartScreen.js file in the screens folder.
  • Import this new CartScreen.js component in the App.js file and create a route for the Cart screen<Route path=’/cart/:id?’ component={CartScreen} />
  • The :id? question mark here means that this id is optional in the route/address. Because if we directly go to the cart page we will not have any id.

28 Cart Functionality

  • Create constants/cartConstants.js and add CART_ADD_ITEM and CART_REMOVE_ITEM constant varaibles to it.
  • Create reducers/cartReducer.js and add the reducer logic.
  • Import cartReducer.js in store.js and add the cartReducer function to the combineReducers argument object.
  • Create actions/cartActions.js. Do the below steps for the building the cart actions.
  • Import axios. We need axios to make a request to /api/products/:id to get the data/fields for that particular product.
  • Import CART_ADD_ITEM from actions/cartActions.js.
  • Then create the addToCart function which will get a (id, qty). We will get both these from the URL params.
  • We will need to use thunk as we are making an async request. So we will return an async function from it. This async function will get (dispatch, getState)dispatch is used for dispatching as usual, but getState will allow us to get our entire state tree. So anything we want like productListproductDetailscart, we can get it using getState.
  • After dispatching, we also want to store this in localStorage.
  • getState().cart.cartItems will give us back a JavaScript object and we can only store strings in the browser localStorage. Hence we have to stringify it. And when we want to take it out and read, we will have to parse it using JSON.parse
  • So we saved it to localStorage but where do we get it to actually fill the state, whenever we reload. We do that in the store.js.
  • We will first see if there is anything in cartItems in the localStorage. If it’s there, then we will add it to the initial state, so always loaded on the app’s first load. If nothing is present in the localStorage then we will just add an empty array.

29. Completing CartScreen.js and creating ‘add to cart’ functionality

  • Build the add to cart functionality.
  • Finish the CartScreen.js component.
  • Add functionality to the Remove Item from cart button. Follow the steps below:
  • Add CART_REMOVE_ITEM to the cartReducer.js file.
  • Create an action named removeFromCart in the cartActions.js file.
  • Fire this action in the removeFromCartHandler function in the CartScreen component.

30. Clean up the backend routes by extracting their logic into controllers

  • In the backend folder, create a folder called controller and create a file called productController.js inside it.
  • Extract all the logic to the productController.js from the routes file. The routes file should now only be for routing and all logic will go in to the controllers.
  • In productRoutes.js instead of using the method router.use(), instead use router.route() and add the route inside and then chain the appropriate methods get, post, put, delete etc. to it. This way we can define different controller logic to the same route. We will see this in sometime.

31. User Authentication Endpoints (Backend Routes)

  • Create routes/userRoutes.js and controllers/userController.js.
  • Start by working on an auth route. So here we want to authenticate a user by email and password. And then we want to send back some data, a token which we can save on the client (browser), so in the frontend (browser) we can use that token to access protected pages/routes (react frontend routes).
  • Import the ../models/userModel.js as we will need it to create new users in the MongoDB database.
  • Create authUser controller function. Inside it, first thing is to get data from the body. This data is on the request object and is something that will be sent here (to the backend) by a POST request and is usually sent via a form on the frontend pages. We can also mimic this sending data using Postman.
  • Before getting the data, make a new folder in rststore Postman collection.. Add a folder called Users & Auth. Inside that create a new request. Name it POST /api/users/login with the url to {{URL}}/api/users/login and add an email & password object to Body of type JSON.
  • Now this object that we add to the body tab in Postman, what will be sent in an object (key-value) on the request object. We extract that from request.body.
  • But in order for parsing this JSON data that we get on the request object from the frontend/Postman, we need to add another middleware in server.js.
  • Add the following line after const app = express part. app.use(express.json())
  • Create the authUser controller function. Also import this into userRoutes.js and add a login route.
  • Also import userRoutes in server.js and add the routes for users..
  • app.use(‘/api/users’, userRoutes)
  • Use the findOne() method on the User model to get the user’s object from the database.
  • Password needs to be encrypted before checking as we are storing encrypted passwords in the database, so add a method on the User Model itself. Edit models/userModel.js and add a method on the userSchema – userSchema.methods.matchPassword.
  • Use this new method in userController.js and finished the implementation.
  • Don’t return the token for now. Just set it to null. Return all other details leaving the password as a json object and also add an else condition.
  • Test this new endpoint in POSTMAN. (start only the server for now)

32. Using Json Web Tokens (JWT)

  • What are JWTs and how do they work?
  • Installation: npm install jsonwebtoken
  • Create a folder called backend/utils. Put all helpers and utility functions here. Inside it create a file named generateToken.js and create the token generation function. Also add the JWT_SECRET to the env as this is needed for the token generation.
  • Import generateToken.js into userController.js and use the function in the response object’s token property (key).
  • Test in Postman. Add this request to Postman.

33. Creating custom Authentication Middleware to accessprotected routes.

  • Add a new request in Postman. GET /api/users/profile with request URL {{URL}}/api/users/profile.
  • Add getUserProfile controller method to userController.js and also export it. Also add the route for this in userRoutes.js.
  • Create a new file named middleware/authMiddleware.js. This middleware will validate the token.
  • Implement the protect middleware function. In our backend we will be getting the authorization tokens in the header object in requests (we will send it that way from React).
  • Import protect into routes/userRoutes.js. We need to add our middleware function here to the /profile endpoint.
  • Implement the complete of the protect middleware function.
  • Once done, we can now use this middleware to any endpoint (route) that we want to be protected, that is only accessible using a valid JWT.
  • Finish implementation of the getUserProfile controller function in userController.js
  • Save the token in Postman, so we don’t have to keep copying and pasting tokens to the Headers. Add Tests to login request so that the token can be set in an environment variable. After that set profile request Auth Type to Bearer Token.

34. User registration

  • Add a new request to Postman: POST /api/users with url as {{URL}}/api/users. This will be a POST request. So a GET request to the same endpoint will give us a total list of users, while a POST request will create a new user.
  • Add a new registerUser controller function to the userController.js file. After that, import this function to userRoutes.js and create a new register route.
  • #### Password Encryption ####
  • The password still isn’t encrypted as we sent it directly to the User.create() function. So to encrypt password while creating a new user and adding it to the database, create a new mongoose middleware.
  • In mongoose, we can set certain things to happen on saves or finds etc. So when we execute the User.create function, before saving to database, we can run some code to encrypt the password and then save.
  • Test the new endpoint in Postman.

35. User Login Reducer and Action

  • Add all constants for the login. Create the file constants/userConstants.js and add all the constants.
  • Create the reducers/userReducer.js file and add the userLoginReducer function. Add all the necessary actions and logic.
  • Import userLoginReducer to store.js and add it to the combineReducers function’s parameter object.
  • Create the actions file in actions/userActions.js and add the action logic. This is pretty much the same as the earlier actions. Only difference here is that we have to add some headers to the axios request, and also store the user data to localStorage.
  • Lastly, since we stored the user data in localStorage, we should load them in the initial state in store.js. Create a variable named userInfoFromStorage and set it to get it’s value from localStorage. In the initialState variable, add another key named userLogin and set it’s value to userInfouserLogin: { userInfo: userInfoFromStorage }

36. User Login Screen

  • Create a new component called components/FormContainer.js which will just be a simple wrapper for our form elements. Just a box with some styling, which we will use to add all our forms in.
  • Create a new screen in screens/LoginScreen.js and write the ui and logic.
  • Import it in App.js and create a route for it.
  • (styling changes overall if required)

37. Implement all the Login – Redux functionality in the LoginScreen component.

  • (styling changes overall if required)

38. Header modification to show User and User Logout feature

  • Modify Header.js. Import redux modules, for running the LOGOUT action and getting access to the state.
    import {useDispatch, useSelector} from ‘react-redux’
  • Import Menu, MenuButton, MenuList, MenuItem from Chakra.
  • Get the userInfo state using useSelector.
  • Also import import { IoChevronDown } from ‘react-icons/io5’
  • Create a logout action in userActions.js.
  • Implement all the logic.

39. User Register, Constants, Reducer, Action and Screen.

  • Add new REGISTER constants to the userConstants.js
  • Create userRegisterReducer in the userReducers.js
  • Import this reducer in store.js and add it to combineReducers
  • Create register action in userActions.js
  • Create the RegisterScreen component and add it to the App.js router.

40. Update User Profile endpoint in the backend

  • Create a updateUserProfile controller method and export it.
  • Import updateUserProfile in userRoutes.js and add a PUT request on the same /profile route. This route will also take the middleware protect as this is a protected endpoint.

41. User Profile Screen and Getting User Details

  • Add USER DETAILS constants to the userConstants.js file.
  • Create userDetailsReducer in userReducer.js and import and add it to the Store.
  • Create and add a getUserDetails action in userActions.js
  • Create the ProfileScreen and add it to Router in App.js

42. Add Update User Profile functionality

  • Add new UPDATE PROFILE constants to the userConstants.js
  • Create userUpdateProfileReducer in the userReducers.js
  • Import this reducer in store.js and add it to combineReducers
  • Create updateUserProfile action in userActions.js
  • Import this action in the ProfileScreen and dispatch it in the submitHandler.

43. Shipping Screen and Save Address

  • Create a new component/screen in screen/ShippingScreen.js and add it to the Router in App.js
  • Complete the ShippingScreen component. Create all the local state required and build the shipping form.
  • In the submitHandler we want to dispatch an action that will save the shipping address to the Redux store.
  • Create a new constant named CART_SAVE_SHIPPING_ADDRESS in the constants/cartConstants.js file.
  • Create a new action named saveShippingAddress in the actions/cartActions.js file.
  • Create a new case CART_SAVE_SHIPPING_ADDRESS in the reducers/cartReducers.js file. Also in the cartReducer function’s initial state object, add another key named shippingAddress and set it to an empty object.

44. Shipping Screen and Save Address

  • Since we are going to store the shippingAddress to localStorage, we also should check if it’s already present in the user’s machine and load it if present. Add the code to the store.js file.
  • Add all Redux related functionality to the ShippingScreen component and finish the implementation.

45. Checkout Steps Component

  • Create he component and then add it to the ShippingScreen component.

46. PaymentScreen – where users can choose the payment method

  • Create the PaymentScreen component in the screens folder.
  • Add CART_SAVE_PAYMENT_METHOD to the cartConstants.js file.
  • Create the savePaymentMethod action function in actions/cartActions.js file.
  • Create a new case CART_SAVE_PAYMENT_METHOD in the reducers/cartReducer.js
  • Import and add PaymentScreen to App.js router.

47. Place Order Screen

  • We will just create a basic screen/page for now. We will do all the real setup only once we have created a backend to actually accept an order.
  • Create a new screen named PlaceOrderScreen.js in the screen folder.
  • Complete the PlaceOrderScreen implementation for now. We will complete this fully when we are done with our order functionality in the backend.
  • Also calculate and set cart.itemsPrice, cart.shippingPrice, cart.taxPrice, cart.totalPrice

48. Backend: Order controller and endpoint (route)

  • Create controllers/orderController.js.
  • Create routes/orderRoutes.js. Import the orderController and connect it here to a endpoint.
  • Lastly add the main endpoint (route) to server.js

49. Create Order

  • Create an constants/orderConstants.js file and add all the constants.
  • Create a new reducer file in reducers/orderReducers.js and add a orderCreateReducer function in it. Import this in store.js and add it to combineReducers.
  • Create a new actions file in actions/orderActions.js and add a createOrder action function.
  • Import createOrder action into the PlaceOrderScreen component and complete the implementation.

50. Get Order By ID (Backend Endpoint)

  • Create the getORderById controller function in the orderController.js file.
  • Add ‘/:id’ route to the orderRoute.js file and attached it to the getOrderbyID controller function.

51. Create the order details reducer and action (frontend)

  • Add new order details related constants in the orderConstants.js file.
  • Create orderDetailsReducer to the orderReducer.js file and connect it in the store.js file.
  • Create a new getOrderDetails function in the orderActions.js file.

52. Create the Order Screen component

  • Create the OrderScreen.js file in screens.
  • Add this new screen to the App.js route.

53. Backend endpoint for updating an order to paid

  • Create a new updateOrderToPaid controller function in the backend/controllers/orderController.js file.
  • Import updateOrderToPaid in the routes/orderRoutes.js and add a route for the endpoint ‘/:id/pay’ making it a PUT request.

54. Order pay reducer and action

  • Add new ORDER_PAY_ constants to the constants/orderConstants.js file in the frontend.
  • Create a new reducer function orderPayReducer in the reducers/orderReducers.js. Import this in store.js and add it to the combineReducers function.
  • Create a new action named payOrder in the actions/orderAction.js file.

55. Adding PayPal Payments

  • Signup for a free Personal or Business account on PayPal.
  • After signup process completion, go to https://developer.paypal.com/developer/applications
  • Go to Sandbox -> Accounts and create 2 Accounts, a personal which you will use to pay and a business to which you will be paying. This will be a sandbox/mock/test environment for working with the PayPal API. You can simply use the 2 default Sandbox Accounts provided by PayPal.

56. Adding PayPal Payments

  • Go to Dashboard -> My Apps & Credentials and make sure Sandbox mode is activated. Click on Create App and follow the process to create a new application. Give the app name ‘rststore’, app type ‘Merchant’ and select the business email (do not use the personal email here). Check everything carefully and then click Create App.
  • After creation you will get your Sandbox API Credentials. We won’t add the Client ID in the frontend. We’ll add it to the backend and create a route to access it.
  • Add the client ID in the .env file and create a route/endpoint in server.js
  • In order to use PayPal, we need to add a script to our site. Visit https://developer.paypal.com/docs/checkout/reference/customize-sdk/ to see the details. We will need to add this script <script src=”https://www.paypal.com/sdk/js?client-id=YOUR_CLIENT_ID”></script> to the orderScreen.
  • Edit the OrderScreen.js file and do all the PayPal implementations.
  • We will use an npm package for adding the PayPal button to the screen. Install the package: npm i react-paypal-button-v2. Make sure you install this in the frontend folder.
  • Add all the paypal functionality and finish the page’s implementation.

57. Show Orders on Profile Page

  • In the backend, create a new controller function, controllers/getMyOrders.js
  • Import this controller in the routes/orderRoutes.js file and connect the route/endpoint.
  • (Optional) Test the endpoint in Postman.
  • Add new ORDER_MY_LIST constants to the constants/orderConstants.js file.
  • Create a reducer named orderMyListReducer in the reducers folder.
  • Import and add this reducer to the combineReducer function’s argument object in store.js
  • Create a new action named listMyOrders and add it to the orderAction.js.
  • Modify the ProfileScreen.js file and implement showing orders in there.

58. Clear state on logout

  • Create ORDER_MY_LIST_RESET in orderConstants.js and add that as a case to the orderMyListReducer function in orderReducer.js
  • Create USER_DETAILS_RESET in userConstants.js and add that as a case to the userDetailsReducer function in userReducer.js
  • Import USER_DETAILS_RESET and ORDER_MY_LIST_RESET and dispatch it in the logout action function.

59. Admin Middleware and Getting Users Endpoint

  • We will create routes that are admin protected and will only be accessible by admin users.
  • For testing purposed, add this as a request to Postman. {{URL}}/api/users. Make a new request for this URL and name this request GET /api/users.
  • In the backend, create a new controller named getUsers in controllers/userController.js
  • Import this controller in routes/userRoutes.js and add it as a get request.
  • Create a new admin auth middleware in middlewares/authMiddlewares.js. This will check if a user is an admin. Import this userRoutes.js and protect the required route.
  • Test route in Postman.

60. Admin User List – Frontend

  • Add new USER_LIST constants to userConstants.js
  • Import these constants and create a new reducer userListReducer in the userReducer.js file. Add it to store.js as well.
  • Create new action called listUsers in userActions.js
  • Create a component called UserListScreen.js in the screens folder. This screen will show admins the complete list of users.
  • Modify the Header.js to show the admin/manage menu and it’s links.

61. Admin Screen page security

  • Edit the UserListScreen.js. Bring in the userLogin state and read the current user login info. If the user is not an admin, then push the user to the ‘/login’ page.
  • Go to the userConstants.js file and add USER_LIST_RESET to it.
  • Import USER_LIST_RESET in the userReducers.js file and add the new case to the userListReducer function.
  • Import USER_LIST_RESET in the userActions.js file and dispatch it in the LOGOUT action. This will clear the users list from redux when an admin logs out.

62. Delete User Functionality (for Admins)

  • Create a new controller function named deleteUser in backend/controllers/userController.js.
  • Import this controller in routes/userRoutes.js and create a new /:id route and add the controller which should be protected by the protect and admin middlewares, to a new route of ‘/:id’.
  • Test this new backend route in Postman. After this, implement these features in the frontend.
  • Add new USER_DELETE_ constants in the frontend/constants/userConstants.js.
  • Add a new reducer function named userDeleteReducer in the reducers/userReducers.js file. Add this reducer to store.js.
  • Add a new action function named deleteUsers to the actions/userActions.js file. Dispatch this action in the UsersListScreen component.

63. Backend endpoints for getting and updating user by it’s ID

  • Add getUserById and updateUser controller methods to the userController.js file. Import these controllers in the userRoutes.js and add the routes.
  • Test these in Postman.

64. User Edit screen and User Details screen components

  • Update the edit link in UserListScreen.js
  • Create a new file named UserEditScreen and implement it.

65. Update user functionality

  • Add new USER_UPDATE_ constants in the userConstants.js file.
  • Create userUpdateReducer reducer function in the userReducers.js and attach it to the store.js
  • Create a new action named updateUser in the userActions.js file. Dispatch this action correctly in the screens/UserEditScreen.js

66. Admin – Product List

  • In the screens folder, create ProductListScreen.js and implement the component.
  • Import and create a route for it in App.js.

67. Admin – Delete Products

  • Create a new deleteProduct controller function in the backend/productController.js file.
  • Import this new controller in routes/productRoutes.js and create an endpoint for it. Protect this route with the product and admin middlewares.
  • (optional) Test the route in Postman.
  • Now implement the feature in the frontend. Add new PRODUCT_DELETE_ constants in the frontend/constants/productConstants.js file.
  • Import these constants in the reducers/productReducers.js file and create a new productDeleteReducer function. Import and add it to the store.js
  • Create a new deleteProduct action function in actions/productActions.js
  • Import the action back in ProductListScreen.js.
  • (for testing only) You can run npm run data:import. Remember to logout and shut down the server before doing this. Also this will reset all the data in the database, including the users and their orders.

68. Create and Update Product Backend Endpoints

  • The Create Product button will immediately add a product with some dummy data and take us to an edit page where we can edit that data.
  • In the productControllers.js file, add two new controller functions, createProduct and updateProduct.
  • Import and add those controller functions in routes/productRoutes.js
  • (optional) Test it in Postman

69. Admin – Create Product Screen

  • Add new PRODUCT_CREATE_ constants in productConstants.js
  • Add new productCreateReducer function to productReducers.js and add it to store.js
  • Add new createProduct action function in productActions.js
  • Complete the ProductListScreen and implement all the functionality.

70. Product Edit Screen

  • Create a new file named ProductEditScreen.js in the screen folder. Implement the entire component.

71. Admin – Update Product Functionality

  • Add new PRODUCT_UPDATE_ constants to the productConstants.js file.
  • Add new productUpdateReducer reducer function to the productReducers.js and add it to store.js
  • Add new updateProduct action function to the productActions.js
  • Dispatch the action in ProductEditScreen and do all required modifications.

72. Image Upload Configuration and Endpoint

  • Install multer in the root folder: npm install multer
  • In the root folder, we will create a folder called uploads. We will store all our uploads in this folder
  • Create uploadRoutes.js file in the routes folder. Complete the upload implementation.
  • In the server.js file create the main route for uploads and make /uploads folder static so we can use it to upload photos.

73. Upload images from the frontend

  • Edit the ProductEditScreen component and implement the upload button.

74. Admin – Order List

  • In controllers/orderController.js, add a new controller function named getOrders.
  • Import getOrders in the routes/orderRoutes.js file and add the route and controller.
  • Add new ORDER_LIST_ constants to the orderConstants.js file.
  • Create new orderListReducer reducer function in the reducers/orderReducers.js file. Add it to the store.js
  • Create new listOrders action function in the actions/orderActions.js file.
  • Create a new OrderListScreen.js to show the orders list to the admin. Add this new component to the App.js and it’s routes.

75. Create Review Endpoint

  • Associate User to reviewSchema. Edit models/productModel.js and add a user object id ref.
  • Add a new createProductReview controller function in controllers/productControllers.js and add it to routes/productRoutes.js and create a route for it.

76. Adding product reviews on the frontend

  • Add new PRODUCT_CREATE_REVIEW_ constants to productConstants.js
  • Create productReviewCreateReducer reducer function in productReducers.js and add it to store.js
  • Create a new createProductReview action function in productActions.js file.
  • Implement the functionality in the ProductScreen.js