Lab guideFullstack

Full Stack Development Sep 18-09-2023

Last updated 29 November 2023

Full Stack Development Sep 18-09-2023

Scratchpads JS

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

// let age = 23;

// if (age >= 18) {
// 	console.log('You are welcome here');
// }

// let num = 33;

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

// let age = 190;

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

let password = 'hello world@123';

if (password.length >= 6) {
    if (password.indexOf(' ') !== -1) {
        console.log('Password cannot contain spaces');
    } else {
        console.log('Valid password');
    }
} else {
    console.log('Password is too short');
}


// let loggedInUser = 'john123';

// if (loggedInUser) {
// 	console.log('Welcome to your dashboard');
// } else {
// 	console.log('Please login to view this content');
// }

// let age = 70;

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

// let day = 1;

// switch (day) {
// 	case 0:
// 	case 1:
// 		console.log('Monday');
// 		break;
// 	case 2:
// 		console.log('Tuesday');
// 		break;
// 	case 3:
// 		console.log('Wednesday');
// 		break;
// 	default:
// 		console.log('Invalid day code');
// }

let status = 'idle';
let color =
    status === 'offline' ? 'red' : status === 'online' ? 'green' : 'yellow';

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

console.log(color);

// status === 'offline' ? console.log('red') : console.log('green');

// if (status === 'offline') {
// 	console.log('red');
// } else {
// 	console.log('green');
// }

// let product1 = ['iPhone 15', 'Apple', 'Some desc...', 500, 100000, true];

// let product1 = {0: 'iPhone 15', 1: 'Apple', 2: 'Some desc...', 3: ''}

let product2 = {
    price: 100000,
    name: 'iPhone 15',
    discounted: true,
    description: 'Some desc...',
    inStock: 500,
    brand: 'Apple',
    1: 'hello',
    'hello world': true,
};
product2.price;
product2[1];
product2['hello world'];

// for (let count = 0; count <= 10; count++) {
// 	console.log(count, 'Hello World');
// }

// console.log('I am out of that loop');

// for (let count = 10; count >= -10; count--) {
// 	console.log(count);
// }

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

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

// console.log(`Total: ${total}`);

// 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.movieName} has a rating of ${movie.rating}`);
// }

// const word = 'Hello World';

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

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

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

// 	for (let j = 0; j < 5; j++) {
// 		console.log(`\t${j} - INNER LOOP`);
// 	}
// }

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

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

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

// let i = 0;

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

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

// while (guess !== target) {
// 	if (guess === 3) {
// 		console.log('Sorry, 3 is an unlucky number');
// 		break;
// 	}
// 	console.log(`Target: ${target} | Guess: ${guess}`);
// 	guess = Math.floor(Math.random() * 10) + 1;
// }

// console.log(`FINAL - Target: ${target} | Guess: ${guess}`);

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

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

// console.log(`FINAL - Target: ${target} | Guess: ${guess}`);

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

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

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

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

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

// let total = 0;
// for (let row of matrix) {
// 	for (let num of row) {
// 		total += num;
// 	}
// }

// console.log(total);

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

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

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

// for (let item of Object.keys(productPrices)) {
// 	console.log(item, productPrices[item]);
// }

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

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

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

// function flipCoin() {
// 	const num = Math.random();

// 	if (num > 0.5) {
// 		console.log('HEADS');
// 	} else {
// 		console.log('TAILS');
// 	}
// }

// flipCoin();
// flipCoin();

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

// function greet() {
// 	// console.log(arguments[0]);
// 	console.log(`${arguments[1]}, ${arguments[0]}`);
// }

// // greet('John Doe', 'hi', 10, 20, 30);
// greet('Jane Smith', 'hello');

// const john = { firstName: 'John', lastName: 'Doe', age: 30 };
// console.log(john.age);
// console.log(john.firstName);
// console.log(john.lastName);
// console.log(john.profesion);

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

function greet(message, name) {
    return `${message}, ${name}`;
}

console.log(greet('Hello', 'John'));

// let result = greet('Hello', 'John');

// console.log('Value of result: ', result);

// let fullName = 'Jane Doe';

// function greet() {
// 	let fullName = 'John Roe';
// 	console.log(fullName);
// }

// function greet2() {
// 	let fullName = 'John Roe';
// 	console.log(fullName);
// }

// greet();

// console.log(fullName);

// let fullName = 'John Smith';

// if (true) {
// 	var fullName = 'Jane Doe';
// 	console.log(fullName);
// }

// console.log(fullName);

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

// console.log('Value of i: ', i);

// var fullName = 'John Doe';
// var fullName = 'Jane Smith';
// console.log(fullName);

// function hello() {
// 	var fullName = 'John';
// 	console.log(fullName);
// }

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

// function outer() {
// 	function inner() {
// 		let fullName = 'John Doe';
// 		console.log(fullName);
// 	}

// 	inner();
// 	console.log(fullName);
// }

// outer();

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

// let world = hello;

// world();

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

// const math = [add, sub];

// console.log(math[0](10, 2));

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

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

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

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

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

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

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

// console.log(math[2](10, 5));

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

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

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

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

// // Example 2
// 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);
// // Example 3
// 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;
// 	};
// }

// const square = raiseBy(2);
// const cube = raiseBy(3);

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

// function isBetween(x, y) {
// 	return function (num) {
// 		return num >= x && num < y;
// 	};
// }

// const isUnderAge = isBetween(0, 18);

// console.log(isUnderAge(25));

// const isUnderAge = isBetween(0, 18);
// const canEnterButNotDrink = isBetween(18, 21);
// const canDrink = isBetween(21, 65);
// const isSenior = isBetween(65, 100);

// console.log(isUnderAge(5));
// console.log(canEnterButNotDrink(20));
// console.log(canDrink(30));
// console.log(isSenior(70));

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

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

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

setInterval(function () {
    console.log('Hello World');
}, 1000);

// hello();

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

// console.log(hello);

// const hello = 'hello world';

// const nums = [1, 2, 32, 34, 23, 2, 3, 45];

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

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

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

// movies.forEach(function (movie, i) {
// 	console.log(`${i} - ${movie.title} has a rating of ${movie.rating}`);
// });

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

// const upperNames = names.map(function (name) {
// 	return name.toUpperCase();
// });
// // const upperNames = [];

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

// console.log(upperNames);

// const nums = [2, 3, 4, 7, 6, 8, 13, 10, 19, 12, 14, 22, 21, 16];
// // const doubles = nums.map(function (num) {
// // 	return num * 2;
// // });

// console.log(doubles);

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

// console.log(numsInfo);

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

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

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

// const square1 = function (num) {
// 	return num * num;
// }

// const square = n => n * n;

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


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

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

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


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

// // const result = movies.find((movie) => movie.includes('Jur'));
// const result = movies.find((movie) => {
// 	return movie[0] == 'T';
// });

// console.log(result);

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

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


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

// const result = nums.filter((num) => num % 2 === 1);
// console.log(result);

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

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

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

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

// console.log(goodBook)
// console.log(georgeBooks)
// console.log(lowRated)
// console.log(booksWithThe)


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

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

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

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

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


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

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

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

// const result = nums.reduce((acc, currVal) => acc * currVal);
// console.log(result);

// acc    currVal
// 1			2
// 3			3
// 6			4
// 10			5
// 15

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

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

// console.log(result);
// acc  currVal
// 21		221
// 221	2
// 221	1
// 221	34
// 221

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

// const result = nums.reduce((acc, currVal) => acc + currVal, 100);

// console.log(result);

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

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

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

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

// const nums = [10, 4];

// console.log(add(...nums));
// const nums = [5, 10, 11, 2, 1];
// console.log(Math.max(...nums));

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

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

// print(...'hello');

// function add(...nums) {
// 	const total = nums.reduce((acc, currVal) => acc + currVal);
// 	return total;
// }

// console.log(add());

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

// printNames('john', 'jack', 'jane', 'jill', 'james');

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

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

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

// console.log(admin, others);

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

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

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

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

// function loop(i) {
// 	if (i > 99) {
// 		return;
// 	} else {
// 		console.log(i);
// 		return loop(i + 1);
// 	}
// }

// loop(0);

// let a = 15;
// let b = "HELLO";
// console.log(b);

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

// console.log(
// 	(function (num) {
// 		return function (x) {
// 			return x ** num;
// 		};
// 	})(2)(8)
// );

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

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

// result(2);

function printProfile({ firstName, lastName, age }) {
    console.log(
        `Hello, my name is ${firstName} ${lastName} and I am ${age} years old.`
    );
}

printProfile({ firstName: 'Jane', lastName: 'Doe', age: 20 });

// // function reverseString(str) {
// // 	// LOGIC
// // 	return; // RESULT
// // }

// // reverseString('hello'); // "olleh"

// // function capitalizeString(str) {
// // 	return '';
// // }

// // capitalizeString('hello world this is something');
// // // "Hello World This Is Something"

// // function isStringEmpty(str) {
// // 	return; // Boolean
// // }
// // isStringEmpty(''); // true

// // function isDigitsPresent(str) {
// // 	return; //
// // }

// // isDigitsPresent('hello wor4ld'); // true

// // function sortNumbers() {}

// // sortNumbers(1, 345, 23, 7, -43, 2, 35, 6, 23); // [-43, 1,2,6,7]

// // function findThreeLargest(...nums) {
// // 	return // array of three largest numbers
// // }

// // findThreeLargest([213,2,3,453,2,6,6,-32,235,2]) // [453, 235, 213]

// // function countVowels(str) {

// // }

// // countVowels("hello"); // 2

// "192.23.45.245" -> "255.255.255.255" -> "0.0.0.0"

// // function checkIfValidIpAddr(ip) {
// // 	return // boolean
// // }

// // checkIfValidIpAddr("400.23.34.56")

// function swapKV(obj) {
// 	return // obj
// }

// swapKV({firstName: "John", age: 20}) // {John: "firstName", 20: "age"}

// function isPalindrome(str) {
// 	return; // bolean
// }

// isPalindrome('kayak'); // true

function isPangram(str) {
    return; // boolean
}

isPangram('The quick brown fox jump');

// rahul@rstforum.co.in

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

// const statistics = getReviewDetails(reviewList);

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

// const info = { [role.toUpperCase()]: username };
// console.log(info);

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

// console.log(addProp({ firstName: 'john' }, 'lastName', 'doe'));

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

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

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

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

// console.log(window);

// const person = {
// 	firstName: 'john',
// 	lastName: 'doe',
// 	age: 20,
// 	greet() {
// 		console.log(this);
// 	},
// };

// greet();
// person.greet();

// console.log(global);

// global.hello = 'hello world';

// let aaaaaaaaahello = 'hello';

// function greet() {
// 	console.log(
// 		`Hello, my name is ${this.firstName} ${this.lastName} and I am ${this.age} years old.`
// 	);
// }

// const person1 = {
// 	firstName: 'john',
// 	lastName: 'doe',
// 	age: 20,
// 	greet,
// };
// const person2 = {
// 	firstName: 'jane',
// 	lastName: 'doe',
// 	age: 22,
// 	greet,
// };

// // greet();
// person1.greet();
// person2.greet();

// const person = {
// 	firstName: 'john',
// 	lastName: 'doe',
// 	age: 20,
// 	greet() {
// 		console.log(`Hello, I am ${this.firstName} ${this.lastName}`);
// 		console.log('Hello World');
// 	},
// };

// const hello = person.greet;

// person.greet();
// hello();

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

// hellos.start();

const person = {
    firstName: 'Jane',
    lastName: 'Doe',
    age: 20,
    greet: function () {
        console.log(
            `Hello my name is ${this.firstName} ${this.lastName} and I am ${this.age} years old.`
        );
    },
};

person.greet();

// const title = document.getElementById('test');
// // console.dir(title);

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

// const ul = document.getElementsByTagName('ul');
// const firstUl = ul[0];

// const lis = firstUl.getElementsByClassName('hello');
// console.log(lis);

// const ul = document.querySelectorAll('.hello');
// console.dir(ul);

// const h1 = document.querySelector('h1');
// h1.innerText = 'this is something new';
// console.log(h1.innerText);
// console.log(document.body.innerText);

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

// const p = document.querySelector('p');
// p.innerHTML = 'Hello world, <strong>this is some</strong> sample content';
// p.innerHTML += 'hellooooo';

// const a = document.querySelector('a');
// a.href = 'https://yahoo.com';
// a.id = 'test';
// a.className = 'helloworld';

const a = document.querySelector('a');
console.log(a.href);
console.log(a.getAttribute('href'));
console.log(a.id);
console.log(a.getAttribute('id'));
a.href = 'https://yahoo.com';
a.setAttribute('href', 'https://duckduckgo.com');

DOM

// const title = document.getElementById('test');
// // console.dir(title);

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

// const ul = document.getElementsByTagName('ul');
// const firstUl = ul[0];

// const lis = firstUl.getElementsByClassName('hello');
// console.log(lis);

// const ul = document.querySelectorAll('.hello');
// console.dir(ul);

// const h1 = document.querySelector('h1');
// h1.innerText = 'this is something new';
// console.log(h1.innerText);
// console.log(document.body.innerText);

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

// const p = document.querySelector('p');
// p.innerHTML = 'Hello world, <strong>this is some</strong> sample content';
// p.innerHTML += 'hellooooo';

// const a = document.querySelector('a');
// a.href = 'https://yahoo.com';
// a.id = 'test';
// a.className = 'helloworld';

const a = document.querySelector('a');
console.log(a.href);
console.log(a.getAttribute('href'));
console.log(a.id);
console.log(a.getAttribute('id'));
a.href = 'https://yahoo.com';
a.setAttribute('href', 'https://duckduckgo.com');


// const ul = document.querySelector('ul');
// // console.log(li.parentElement.parentElement.parentElement);
// console.log(ul.children);

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

// for (let li of lis) {
// 	setInterval(() => {
// 		li.innerText = Math.random();
// 	}, 5);
// }

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

// li.style.backgroundColor = 'red';
// li.style.color = 'white';
// li.style.fontSize = '30px';

const colors = [
    'red',
    'green',
    'blue',
    'orange',
    'maroon',
    'yellow',
    'purple',
    'pink',
    'grey',
    'amber',
    'aqua',
    'peach',
];

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

// for (let li of lis) {
// 	setInterval(() => {
// 		li.innerText = Math.random();

// 		const randomNum1 = Math.floor(Math.random() * colors.length);
// 		const randomNum2 = Math.floor(Math.random() * colors.length);
// 		const randomNum3 = Math.floor(Math.random() * colors.length);
// 		li.style.color = colors[randomNum1];
// 		li.style.backgroundColor = colors[randomNum2];
// 		document.body.style.backgroundColor = colors[randomNum3];
// 	}, 100);
// }

// const li = document.querySelector('li');
// // li.className = 'todo done';
// // console.log(li.classList);
// li.classList.add('done');
// li.classList.remove('todo');
// li.classList.toggle('done');

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

// const h1 = document.createElement('h1'); // <h1></h1>
// h1.innerText = 'This is some sample text';
// h1.style.fontSize = '50px';
// h1.style.textDecoration = 'underline';
// h1.style.color = 'blue';
// h1.id = 'title';

// const section = document.createElement('section');
// section.appendChild(h1);

// root.appendChild(section);

// const ul = document.querySelector('ul');
// const li = document.querySelectorAll('li')[1];

// const newListItem = document.createElement('li');
// newListItem.innerText = 'Hello World';
// newListItem.style.color = 'red';

// ul.insertBefore(newListItem, li);
// // ul.appendChild(newListItem)

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

// // p.insertAdjacentElement('afterend', b);
// // p.prepend(b, i);
// p.remove();

// const btn = document.querySelector('button');
// btn.onclick = function () {
// 	console.log('Hello World');
// };
// btn.onclick = function () {
// 	console.log('Goodbye World');
// };

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

// btn.addEventListener('click', function () {
// 	console.log('Hello World');
// 	const random = Math.floor(Math.random() * colors.length);
// 	document.body.style.backgroundColor = colors[random];
// });
// btn.addEventListener('mousedown', function () {
// 	console.log('Goodbye World');
// });

// window.addEventListener('scroll', function () {
// 	console.log(Math.random());
// });

const btn = document.querySelector('button');
btn.style.position = 'relative';

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 WIN!';
    document.body.style.backgroundColor = 'green';
});


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

// form.addEventListener('submit', function (event) {
// 	event.preventDefault();

// 	const li = document.createElement('li');
// 	li.innerText = event.target[0].value;
// 	li.addEventListener('click', function () {
// 		li.classList.toggle('done');
// 	});

// 	const btn = document.createElement('button');
// 	btn.innerText = 'Delete';
// 	btn.style.marginLeft = '30px';
// 	btn.addEventListener('click', function () {
// 		li.remove();
// 	});

// 	li.append(btn);
// 	ul.append(li);
// 	event.target[0].value = '';
// });

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

// function square(x) {
// 	return multiply(x, x);
// }

// function rightTriangle(x, y, z) {
// 	return square(x) + square(y) === square(z);
// }

// rightTriangle(1, 2, 3);

// console.log('The first log');
// alert('Hello World');
// console.log('The second log');

console.log('The first log');
setTimeout(function () {
    console.log('Hello World');
}, 5000);
console.log('The second log');

Scratchpad #13 14 15

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

// form.addEventListener('submit', function (event) {
// 	event.preventDefault();

// 	const li = document.createElement('li');
// 	li.innerText = event.target[0].value;
// 	li.addEventListener('click', function () {
// 		li.classList.toggle('done');
// 	});

// 	const btn = document.createElement('button');
// 	btn.innerText = 'Delete';
// 	btn.style.marginLeft = '30px';
// 	btn.addEventListener('click', function () {
// 		li.remove();
// 	});

// 	li.append(btn);
// 	ul.append(li);
// 	event.target[0].value = '';
// });

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

// function square(x) {
// 	return multiply(x, x);
// }

// function rightTriangle(x, y, z) {
// 	return square(x) + square(y) === square(z);
// }

// rightTriangle(1, 2, 3);

// console.log('The first log');
// alert('Hello World');
// console.log('The second log');

console.log('The first log');
setTimeout(function () {
    console.log('Hello World');
}, 5000);
console.log('The second log');


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

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

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

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

// console.log(willGetAPlayStation);

// willGetAPlayStation
// 	.then(() => {
// 		console.log('Thank you uncle');
// 	})
// 	.catch(() => {
// 		console.log('#@$@#$#@ uncle');
// 	});

// function makePlayStationPromise() {
// 	return new Promise((resolve, reject) => {
// 		setTimeout(() => {
// 			const rand = Math.random();
// 			if (rand < 0.5) {
// 				resolve();
// 			} else {
// 				reject();
// 			}
// 		}, 3000);
// 	});
// }

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

function 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',
                '/users/1': {
                    id: 1,
                    username: 'johndoe',
                    topPostId: 53231,
                    city: 'mumbai',
                },
                '/users/5': {
                    id: 1,
                    username: 'janedoe',
                    topPostId: 32443,
                    city: 'pune',
                },
                '/posts/53231': {
                    id: 1,
                    title: 'Really amazing post',
                    slug: 'really-amazing-post',
                },
            };

            const data = pages[url];

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

// fakeRequest('/users')
// 	.then((response) => {
// 		const userId = response.data[0].id;
// 		fakeRequest(`/users/${userId}`)
// 			.then((response) => {
// 				const postId = response.data.topPostId;
// 				fakeRequest(`/posts/${postId}`)
// 					.then((response) => {
// 						console.log(response);
// 					})
// 					.catch((error) => {
// 						console.log(error);
// 					});
// 			})
// 			.catch((error) => {
// 				console.log(error);
// 			});
// 	})
// 	.catch((error) => {
// 		console.log(error);
// 	});

// fakeRequest('/users')
// 	.then((response) => {
// 		const userId = response.data[0].id;
// 		return fakeRequest(`/users/${userId}`);
// 	})
// 	.then((response) => {
// 		const postId = response.data.topPostId;
// 		return fakeRequest(`/posts/${postId}`);
// 	})
// 	.then((response) => {
// 		console.log(response);
// 	})
// 	.catch((error) => {
// 		console.log(error);
// 	});

/**
 * @description Function that adds two numbers
 * @param {number} a
 * @param {number} b
 * @returns {number}
 */
function add1(a, b) {
    return a + b;
}

console.log(add1(undefined, false));


// fetch('https://pokeapi.co/api/v2/pokemon')
// 	.then((response) => {
// 		return response.json();
// 	})
// 	.then((data) => {
// 		console.log(data);
// 	})
// 	.catch((error) => {
// 		console.log(error);
// 	});

// fetch('https://pokeapi.co/api/v2/pokemon')
// 	.then((response) => {
// 		console.log('IN THE SUCCESS/THEN BLOCK');
// 		if (!response.ok) {
// 			throw new Error();
// 		}
// 		return response.json();
// 	})
// 	.then((data) => {
// 		console.log(data);
// 	})
// 	.catch((error) => {
// 		console.log('IN THE ERROR BLOCK');
// 		console.log(error);
// 	});

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

axios
    .get('https://pokeapi.co/api/v2/pokemon?limit=100000')
    .then((response) => {
        const pokemons = response.data.results;

        for (let pokemon of pokemons) {
            axios.get(pokemon.url).then((res) => {
                const div = document.createElement('div');
                div.style.display = 'flex';
                div.style.flexDirection = 'column';
                div.style.alignItems = 'center';

                const h4 = document.createElement('h4');
                h4.innerText = res.data.name;
                h4.style.textTransform = 'capitalize';
                h4.style.fontSize = '30px';

                const img = document.createElement('img');
                img.src = res.data.sprites.other['official-artwork'].front_default;
                img.style.width = '100%';

                div.append(img, h4);
                root.append(div);
            });
        }
    })
    .catch((error) => {
        console.log('In the error block');
        console.log(error);
    });
Learn this on the racks

Reading it is one thing. Configuring it is another.

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