Full Stack Morning Oct-8-2021
Scratchpad #2 – JS
// let isUserLoggedIn = true;
// if (isUserLoggedIn) {
// console.log("This is the result");
// }
// console.log("This is the last line outside the conditional");
// let num = 12;
// if (num % 2 === 0) {
// console.log("Number is even");
// } else {
// console.log("Number is odd");
// }
// let age = 70;
// 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("You are not allowed");
// }
// let age = 67;
// if (age > 18) {
// if (age >= 65) {
// console.log("Drinks FREE!");
// } else if (age >= 21) {
// console.log("Drinks Allowed");
// } else {
// console.log("You can enter but you cannot drink");
// }
// } else {
// console.log("Get lost!");
// }
// let password = "helloworld@123";
// if (password.length >= 6) {
// if (password.indexOf(" ") !== -1) {
// console.log("Password cannot include spaces");
// } else {
// console.log("Valid Password");
// }
// } else {
// console.log("password is too short");
// }
// let age = 20;
// 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("You are not allowed");
// }
// let day = 3;
// if (day === 1) {
// console.log("It's monday");
// } else if (day === 2) {
// console.log("It's tuesday");
// } else if (day === 3) {
// console.log("It's Wednesday");
// } else {
// console.log("Invalid day code");
// }
// let day = 1;
// switch (day) {
// case 1:
// case 2:
// console.log("Tuesday");
// break;
// case 3:
// 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("This is not a day");
// }
// let age = 70;
// age >= 18 ? console.log("You can enter") : console.log("Not allowed");
// let canEnter = age >= 18 ? true : false;
// age >= 18 && age < 21
// ? console.log("You can enter")
// : age >= 21 && age < 65
// ? console.log("You can drink")
// : age >= 65
// ? console.log("Drinks are free")
// : console.log("Get lost");
let cart = 10;
console.log("You have " + cart + " items in your cart.");
console.log(`You have ${cart} items in your cart`);
Scratchpad #3 & #4
cart = ["iPhone 12", "Macbook Air", "Macbook m1 max"];
// let removedItem = 'Macbook m1 max';
let hello = console.log("Hello world");
let deletedItem = cart.pop();
console.log(hello);
console.log(deletedItem);
// 'maroon'
const nums2 = [1, 2, 3, 4, 5];
const nums2 = { 0: 1, 1: 2, 2: 3, 3: 4, 4: 5, length: 5 };
Scratchpad #5
// for (let i = 0; i < 10; i++) {
// console.log(`OUTER LOOP - ${i}`);
// for (let j = 0; j < 10; j++) {
// console.log(` INNER LOOP - ${j}`);
// for (let k = 0; k < 10; k++) {
// console.log(` EVEN MORE INNER LOOP - ${k}`);
// }
// }
// }
// function greet() {
// console.log('Hello World');
// console.log('Hello Universe');
// }
// // greet();
// for (let i = 0; i < 10; i++) {
// greet();
// }
// function rollDie() {
// let roll = Math.floor(Math.random() * 6) + 1;
// console.log(`Rolled: ${roll}`);
// }
// rollDie();
// for (let i = 0; i < 5; i++) {
// rollDie();
// }
// function throwDice() {
// rollDie();
// rollDie();
// }
// throwDice();
// console.log('Hello World');
// function greet(name) {
// console.log(`Hello ${name}, how are you?`);
// }
// greet('John');
// greet('Jane');
// function greet(name, message) {
// console.log(`${message}, ${name}`);
// }
// greet();
// function add(num1, num2) {
// console.log(num1 + num2);
// }
// add(10, 23);
// 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(6);
function greet(name) {
return `Hello ${name}, how are you?`;
}
// let result = greet('John Doe');
// console.log(result);
// function sub(a, b) {
// console.log(a - b);
// }
// console.log(sub(4, 7));
// let message = 'Hello World!';
// function greet() {
// // let message = 'Hello, how are you?!';
// console.log(message);
// }
// console.log(message);
// function greet() {
// console.log(Math);
// }
// greet();
// console.log(Math);
// function greet() {
// var name = 'John Doe';
// console.log(name);
// }
// console.log(name);
// greet();
// if (true) {
// var first_name = 'John';
// var last_name = 'Doe';
// console.log(first_name + ' ' + last_name);
// }
// console.log(first_name);
// console.log(last_name);
// for (var i = 0; i < 10; i++) {
// console.log(i);
// }
// for (var i; i < 20; i++) {
// console.log(i);
// }
// console.log(i);
function outer() {
// let movie = 'Avengers';
function inner() {
let movie = 'John Wick';
let ratings = `${movie} has a rating of 4.2`;
console.log(ratings);
}
console.log(movie);
inner();
}
outer();
Scratchpad #7
// function square(x) {
// return x * x;
// }
// // console.log(square(10));
// const square = function (x) {
// return x * x;
// };
// // // console.log(square(8));
// // const maths = {
// // PI: 3.14,
// // add: function (a, b) {
// // return a + b;
// // },
// // subtract: function (a, b) {
// // return a - b;
// // },
// // multiply: function (a, b) {
// // return a * b;
// // },
// // };
// // console.log(maths.add(10, 4));
// // maths.subtract(10, 6)
// // Math.round()
// // const console = {
// // log: function() {},
// // error: function() {},
// // warn: function() {}
// // }
// // console.log()
// const someArr = [
// 10,
// true,
// [1, 2, 3],
// function (a, b) {
// return a + b;
// },
// function (name) {
// console.log(`Hello ${name}`);
// },
// square,
// ];
// // console.log(someArr[3](10, 4));
// console.log(someArr[5](5));
// 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;
// }
// const operations = [add, sub, mul, div];
// for (let op of operations) {
// let result = op(10, 2);
// console.log(result);
// }
// const nums = [1324, 232, 311, 422, 500, -6];
// for (let n of nums) {
// console.log(n);
// }
// for (let n = 0; n < nums.length; n++) {
// console.log(nums[n]);
// }
// function multipleGreets(fn) {
// }
// const multipleGreets = function (bro) {
// bro();
// bro();
// };
// function sayHello() {
// console.log('Hello World');
// }
// function sayGoodbye() {
// console.log('Goodbye World');
// }
// multipleGreets(sayGoodbye);
// function repeat(func, num) {
// for (let i = 0; i < num; i++) {
// func();
// }
// }
// repeat(sayHello, 10);
// function randomPick(f1, f2) {
// let randNum = Math.random();
// if (randNum < 0.5) {
// f1();
// } else {
// f2();
// }
// }
// randomPick(sayGoodbye, sayHello);
// function raiseBy(num) {
// // inner function has access
// // to parent function's scope
// return function (x) {
// return x ** num;
// };
// }
// const raiseBy3 = raiseBy(3);
// const power10 = raiseBy(10);
// console.log(power10(2));
// const resultFunction = raiseBy(4);
// // const resultFunction = function (x) {
// // return x ** 4;
// // };;
// console.log(resultFunction(10));
// function isBetween(x, y) {
// return function (num) {
// return num >= x && num <= y;
// };
// }
// // const isUnderAge = function (num) {
// // return num >= 0 && num <= 18;
// // };
// const isUnderAge = isBetween(1, 18);
// const canEnterButNotDrink = isBetween(18, 21);
// const canDrink = isBetween(21, 65);
// const isSenior = isBetween(65, 100);
// // console.log(isUnderAge(82));
// console.log(isSenior(120));
// const sayHello = function () {
// console.log('Hello World');
// };
// setTimeout(sayHello, 3000);
// setTimeout(function () {
// console.log('Say goodbye');
// }, 5000);
sayHello();
console.log(firstName, lastName);
function sayHello() {
console.log('Hello World!');
}
// var firstName;
// var lastName;
var firstName = 'John';
var lastName = 'Doe';
// let firstName = 'John';
// let lastName = 'Doe';
const sayHello = function () {
console.log('Hello World');
};
Scratchpad #7
// const result = [];
// for (let obj of data) {
// if (obj.color === 'red') {
// result.push(obj);
// }
// }
// console.log(result);
// function filterArrOfObjs(arr, filterKey, filterValue) {
// const result = [];
// for (let obj of arr) {
// if (obj[filterKey] === filterValue) {
// result.push(obj);
// }
// }
// return result;
// }
// const data = [
// { color: 'red', price: 40 },
// { color: 'blue', price: 20 },
// { color: 'green', price: 30 },
// { color: 'red', price: 30 },
// ];
// const result = filterArrOfObjs(data, 'price', 30);
// console.log(result);
// const nums = [9, 2, 4, 6, 2, 3, 7, 6];
// for (let num of nums) {
// console.log(num);
// }
// nums.forEach(function (num) {
// // console.log(`The value is ${num * 4}`);
// if (num % 2 === 0) {
// console.log(`Number ${num} is even`);
// }
// });
// 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, idx) {
// console.log(
// `${idx + 1}: ${movie.title.toUpperCase()} has a rating of ${movie.rating}`
// );
// });
// const names = ['john', 'jack', 'jane', 'james'];
// const result = names.map(function (name) {
// return `<div><p>${name}</p></div>`;
// });
// console.log(result);
// const nums = [2, 3, 4, 7, 6, 8, 13, 10, 19, 12, 14, 22, 21, 16];
// const numDetails = nums.map(function (num) {
// return {
// number: num,
// isEven: num % 2 === 0,
// };
// });
// console.log(numDetails);
// const doubles = nums.map(function (num) {
// return num * 2;
// });
// console.log(doubles);
// console.log(
// `Doubling all the numbers ${nums.map(function (num) {
// return num * 2;
// })}`
// );
// const doubles = nums.map(function (num) {
// return num * 2;
// });
// const doubles = nums.map((num) => {
// return num * 2;
// });
// console.log(doubles);
// const square = function (x) {
// console.log(x * x);
// };
// const square = (x) => {
// return x * x;
// };
// const square = x => {
// return x * x;
// };
// const add = (x, y) => {
// return x + y;
// };
// const greet = () => {
// console.log('Hello World');
// };
// console.log(square(10));
// console.log(add(10, 4));
// greet();
// const square = x => {
// return x * x;
// };
// const square = x => (
// x * x
// );
// const square = x => (x * x);
// const square = x => x * x;
// const square = x => {
// const result = []
// return x * x
// };
// console.log(square(5));
// const doubles = nums.map(num => num * 2);
// console.log(doubles);
// const parityList = nums.map(n => (n % 2 === 0 ? 'Even' : 'Odd'));
// console.log(parityList);
// let movies = ['The Terminator', 'The Avengers', 'Jurassic Park', 'Titanic'];
// // const result = movies.find((movie) => {
// // return movie.includes('the');
// // });
// const result = movies.find((movie) => movie.includes('the'));
// 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 goodBook = books.find((book) => book.rating >= 4.3);
// const georgeBook = books.find((b) => b.author.includes('George'));
// const lowRated = books.find((book) => {
// return book.rating < 4;
// });
// console.log(goodBook);
// console.log(georgeBook);
// console.log(lowRated);
// const goodBooks = books.filter((book) => book.rating >= 4.3);
// console.log(goodBooks);
// const filterByRating = (collection, rating) => {
// return collection.filter((item) => item.rating >= rating);
// };
/*
* Filter a collection based on it's ratings
*
* @param collection: Array
* @param rating: Number
* @param condition: 'less than' | 'greater than'
*
* Usage example:
* filterByRating(books, 4.0, 'less than')
*
*/
// const filterByRating = (collection, rating, condition) => {
// if (condition === 'less than') {
// return collection.filter((i) => i.rating <= rating);
// } else if (condition === 'greater than') {
// return collection.filter((i) => i.rating >= rating);
// } else {
// return 'UNKNOWN CONDITION';
// }
// };
// console.log(filterByRating(books, 4.0, 'greater than'));
// function filterByRating(collection, rating) {
// return collection.filter(function (item) {
// return item.rating >= rating;
// });
// }
// console.log(filterByRating(books, 4.0));
// const names = ['jack', 'james', 'john', 'jane', 'josh', 'brad'];
// const result = names.every((name) => name[0] === 'j');
// const result2 = names.every((name) => name.length > 3);
// console.log(result2);
// const names = ['jack', 'james', 'john', 'jane', 'josh', 'brad'];
// const result = names.some((name) => name[0] === 'z');
// console.log(result);
// const prices = [500.4, 211, 23, 5, 4, 22.2, -23.2, 9233];
// console.log(prices);
// prices.sort((a, b) => b - a);
// // console.log(prices.sort((a, b) => a - b));
// // console.log(prices.sort((a, b) => b - a));
// console.log(prices);
// const nums = [3, 2, 4, 6, 9];
// const result = nums.reduce((accumulator, currentValue) => {
// return accumulator + currentValue;
// });
// console.log(result);
// const nums = [2, 4, 3, 1];
// console.log(nums.reduce((acc, currVal) => acc + currVal, 100));
let nums = [21, 221, 2, 1, 34, 123, 4342, 56, 4];
const maxVal = nums.reduce((acc, currVal) => {
if (currVal > acc) {
return currVal;
}
return acc;
});
console.log(maxVal);
Scratchpad #8
// const multiply = (x, y) => {
// // old way of setting default
// // parameter values
// if (typeof y === 'undefined') {
// y = 1;
// }
// // // using ternary operator instead
// // // of an if statement
// // y = typeof y === 'undefined' ? 1 : y
// return x * y;
// };
// console.log(multiply(5));
// const multiply = (x = 1, y = 1) => {
// return x * y;
// };
// console.log(multiply());
// const greet = (name = 'Unknown', msg) => {
// return `${msg}, ${name}`;
// };
// console.log(greet('John', 'Hey')); // "Hey John"
// console.log(greet()); // "Hi Ukn"
// console.log(greet('John'));
// console.log(greet('john'));
// const nums = [1, 45, 2, 655, 23, 12, 98, 57, 12, 0, -123];
// const result = Math.max(...nums);
// const result2 = Math.min(...nums);
// console.log(result);
// console.log(result2);
// function printVals(a, b, c) {
// console.log(a);
// console.log(b);
// console.log(c);
// }
// printVals('jane', 'john', 'jack');
// const names = ['james', 'jackson', 'jason', 'john', 'jamie'];
// printVals(...names);
// printVals('h', 'e', 'l', 'l', 'o');
// printVals(...'hello');
// function add(x, y) {
// return x + y;
// }
// const add = (...nums) => {
// // console.log(nums);
// return nums.reduce((acc, currVal) => acc + currVal);
// };
// // console.log(add(10, 4, 45));
// console.log(add(10, 2, 3, 55, 2, 323, 312, 2, 42, 3));
// function printNames(name1, name2, ...others) {
// console.log(name1);
// console.log(name2);
// console.log(others);
// }
// printNames(
// 'John',
// 'Jack',
// 'Jane',
// 'James',
// 'Jones',
// 'Jonas',
// 'Jessica',
// 'Jamal'
// );
// const users = ['john', 'jane', 'jack'];
// // const admin = users[0];
// // const mod = users[1];
// // const sub = users[2];
// // const [admin, moderator, subscriber] = users;
// // const [admin, , subscriber] = users;
// const [admin, ...others] = users;
// // console.log(admin, mod, sub);
// // console.log(admin, subscriber);
// console.log(admin, others);
// const user = {
// firstName: 'John',
// lastName: 'Doe',
// email: 'john.doe@gmail.com',
// phone: 99982234567,
// address: { city: 'Mumbai', pin: '400050' },
// };
// // const { firstName, lastName, email: emailAddress, phone } = user;
// // const { firstName, lastName, ...others } = user;
// // console.log(firstName, lastName, emailAddress, phone);
// // console.log(firstName, lastName, others);
// const {
// address: { city: shahar, pin },
// } = user;
// console.log(shahar, pin);
const user = {
firstName: 'John',
lastName: 'Doe',
emailAddress: 'john.doe@gmail.com',
};
// const profile = (userData) => {
// console.log(
// `${userData.firstName} ${userData.lastName} has an email address: ${userData.emailAddress}`
// );
// };
// const profile = ({ firstName, lastName, emailAddress }) => {
// console.log(`${firstName} ${lastName} has an email address: ${emailAddress}`);
// };
// profile(user);
// profile({ firstName: 'Jack', lastName: 'Ma', emailAddress: 'jack@baba.com' });
// const filterProducts = (productsArr, filterKey, filterValue, )
const products = [
{
id: 1,
title: 'Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops',
price: 109.95,
description:
'Your perfect pack for everyday use and walks in the forest. Stash your laptop (up to 15 inches) in the padded sleeve, your everyday',
category: "men's clothing",
image: 'https://fakestoreapi.com/img/81fPKd-2AYL._AC_SL1500_.jpg',
rating: {
rate: 3.9,
count: 120,
},
},
{
id: 2,
title: 'Mens Casual Premium Slim Fit T-Shirts ',
price: 22.3,
description:
'Slim-fitting style, contrast raglan long sleeve, three-button henley placket, light weight & soft fabric for breathable and comfortable wearing. And Solid stitched shirts with round neck made for durability and a great fit for casual fashion wear and diehard baseball fans. The Henley style round neckline includes a three-button placket.',
category: "men's clothing",
image:
'https://fakestoreapi.com/img/71-3HjGNDUL._AC_SY879._SX._UX._SY._UY_.jpg',
rating: {
rate: 4.1,
count: 259,
},
},
{
id: 3,
title: 'Mens Cotton Jacket',
price: 55.99,
description:
'great outerwear jackets for Spring/Autumn/Winter, suitable for many occasions, such as working, hiking, camping, mountain/rock climbing, cycling, traveling or other outdoors. Good gift choice for you or your family member. A warm hearted love to Father, husband or son in this thanksgiving or Christmas Day.',
category: "men's clothing",
image: 'https://fakestoreapi.com/img/71li-ujtlUL._AC_UX679_.jpg',
rating: {
rate: 4.7,
count: 500,
},
},
{
id: 4,
title: 'Mens Casual Slim Fit',
price: 15.99,
description:
'The color could be slightly different between on the screen and in practice. / Please note that body builds vary by person, therefore, detailed size information should be reviewed below on the product description.',
category: "men's clothing",
image: 'https://fakestoreapi.com/img/71YXzeOuslL._AC_UY879_.jpg',
rating: {
rate: 2.1,
count: 430,
},
},
{
id: 5,
title:
"John Hardy Women's Legends Naga Gold & Silver Dragon Station Chain Bracelet",
price: 695,
description:
"From our Legends Collection, the Naga was inspired by the mythical water dragon that protects the ocean's pearl. Wear facing inward to be bestowed with love and abundance, or outward for protection.",
category: 'jewelery',
image: 'https://fakestoreapi.com/img/71pWzhdJNwL._AC_UL640_QL65_ML3_.jpg',
rating: {
rate: 4.6,
count: 400,
},
},
{
id: 6,
title: 'Solid Gold Petite Micropave ',
price: 168,
description:
'Satisfaction Guaranteed. Return or exchange any order within 30 days.Designed and sold by Hafeez Center in the United States. Satisfaction Guaranteed. Return or exchange any order within 30 days.',
category: 'jewelery',
image: 'https://fakestoreapi.com/img/61sbMiUnoGL._AC_UL640_QL65_ML3_.jpg',
rating: {
rate: 3.9,
count: 70,
},
},
{
id: 7,
title: 'White Gold Plated Princess',
price: 9.99,
description:
"Classic Created Wedding Engagement Solitaire Diamond Promise Ring for Her. Gifts to spoil your love more for Engagement, Wedding, Anniversary, Valentine's Day...",
category: 'jewelery',
image: 'https://fakestoreapi.com/img/71YAIFU48IL._AC_UL640_QL65_ML3_.jpg',
rating: {
rate: 3,
count: 400,
},
},
{
id: 8,
title: 'Pierced Owl Rose Gold Plated Stainless Steel Double',
price: 10.99,
description:
'Rose Gold Plated Double Flared Tunnel Plug Earrings. Made of 316L Stainless Steel',
category: 'jewelery',
image: 'https://fakestoreapi.com/img/51UDEzMJVpL._AC_UL640_QL65_ML3_.jpg',
rating: {
rate: 1.9,
count: 100,
},
},
{
id: 9,
title: 'WD 2TB Elements Portable External Hard Drive - USB 3.0 ',
price: 64,
description:
'USB 3.0 and USB 2.0 Compatibility Fast data transfers Improve PC Performance High Capacity; Compatibility Formatted NTFS for Windows 10, Windows 8.1, Windows 7; Reformatting may be required for other operating systems; Compatibility may vary depending on user’s hardware configuration and operating system',
category: 'electronics',
image: 'https://fakestoreapi.com/img/61IBBVJvSDL._AC_SY879_.jpg',
rating: {
rate: 3.3,
count: 203,
},
},
{
id: 10,
title: 'SanDisk SSD PLUS 1TB Internal SSD - SATA III 6 Gb/s',
price: 109,
description:
'Easy upgrade for faster boot up, shutdown, application load and response (As compared to 5400 RPM SATA 2.5” hard drive; Based on published specifications and internal benchmarking tests using PCMark vantage scores) Boosts burst write performance, making it ideal for typical PC workloads The perfect balance of performance and reliability Read/write speeds of up to 535MB/s/450MB/s (Based on internal testing; Performance may vary depending upon drive capacity, host device, OS and application.)',
category: 'electronics',
image: 'https://fakestoreapi.com/img/61U7T1koQqL._AC_SX679_.jpg',
rating: {
rate: 2.9,
count: 470,
},
},
{
id: 11,
title:
'Silicon Power 256GB SSD 3D NAND A55 SLC Cache Performance Boost SATA III 2.5',
price: 109,
description:
'3D NAND flash are applied to deliver high transfer speeds Remarkable transfer speeds that enable faster bootup and improved overall system performance. The advanced SLC Cache Technology allows performance boost and longer lifespan 7mm slim design suitable for Ultrabooks and Ultra-slim notebooks. Supports TRIM command, Garbage Collection technology, RAID, and ECC (Error Checking & Correction) to provide the optimized performance and enhanced reliability.',
category: 'electronics',
image: 'https://fakestoreapi.com/img/71kWymZ+c+L._AC_SX679_.jpg',
rating: {
rate: 4.8,
count: 319,
},
},
{
id: 12,
title:
'WD 4TB Gaming Drive Works with Playstation 4 Portable External Hard Drive',
price: 114,
description:
"Expand your PS4 gaming experience, Play anywhere Fast and easy, setup Sleek design with high capacity, 3-year manufacturer's limited warranty",
category: 'electronics',
image: 'https://fakestoreapi.com/img/61mtL65D4cL._AC_SX679_.jpg',
rating: {
rate: 4.8,
count: 400,
},
},
{
id: 13,
title: 'Acer SB220Q bi 21.5 inches Full HD (1920 x 1080) IPS Ultra-Thin',
price: 599,
description:
'21. 5 inches Full HD (1920 x 1080) widescreen IPS display And Radeon free Sync technology. No compatibility for VESA Mount Refresh Rate: 75Hz - Using HDMI port Zero-frame design | ultra-thin | 4ms response time | IPS panel Aspect ratio - 16: 9. Color Supported - 16. 7 million colors. Brightness - 250 nit Tilt angle -5 degree to 15 degree. Horizontal viewing angle-178 degree. Vertical viewing angle-178 degree 75 hertz',
category: 'electronics',
image: 'https://fakestoreapi.com/img/81QpkIctqPL._AC_SX679_.jpg',
rating: {
rate: 2.9,
count: 250,
},
},
{
id: 14,
title:
'Samsung 49-Inch CHG90 144Hz Curved Gaming Monitor (LC49HG90DMNXZA) – Super Ultrawide Screen QLED ',
price: 999.99,
description:
'49 INCH SUPER ULTRAWIDE 32:9 CURVED GAMING MONITOR with dual 27 inch screen side by side QUANTUM DOT (QLED) TECHNOLOGY, HDR support and factory calibration provides stunningly realistic and accurate color and contrast 144HZ HIGH REFRESH RATE and 1ms ultra fast response time work to eliminate motion blur, ghosting, and reduce input lag',
category: 'electronics',
image: 'https://fakestoreapi.com/img/81Zt42ioCgL._AC_SX679_.jpg',
rating: {
rate: 2.2,
count: 140,
},
},
{
id: 15,
title: "BIYLACLESEN Women's 3-in-1 Snowboard Jacket Winter Coats",
price: 56.99,
description:
'Note:The Jackets is US standard size, Please choose size as your usual wear Material: 100% Polyester; Detachable Liner Fabric: Warm Fleece. Detachable Functional Liner: Skin Friendly, Lightweigt and Warm.Stand Collar Liner jacket, keep you warm in cold weather. Zippered Pockets: 2 Zippered Hand Pockets, 2 Zippered Pockets on Chest (enough to keep cards or keys)and 1 Hidden Pocket Inside.Zippered Hand Pockets and Hidden Pocket keep your things secure. Humanized Design: Adjustable and Detachable Hood and Adjustable cuff to prevent the wind and water,for a comfortable fit. 3 in 1 Detachable Design provide more convenience, you can separate the coat and inner as needed, or wear it together. It is suitable for different season and help you adapt to different climates',
category: "women's clothing",
image: 'https://fakestoreapi.com/img/51Y5NI-I5jL._AC_UX679_.jpg',
rating: {
rate: 2.6,
count: 235,
},
},
{
id: 16,
title:
"Lock and Love Women's Removable Hooded Faux Leather Moto Biker Jacket",
price: 29.95,
description:
'100% POLYURETHANE(shell) 100% POLYESTER(lining) 75% POLYESTER 25% COTTON (SWEATER), Faux leather material for style and comfort / 2 pockets of front, 2-For-One Hooded denim style faux leather jacket, Button detail on waist / Detail stitching at sides, HAND WASH ONLY / DO NOT BLEACH / LINE DRY / DO NOT IRON',
category: "women's clothing",
image: 'https://fakestoreapi.com/img/81XH0e8fefL._AC_UY879_.jpg',
rating: {
rate: 2.9,
count: 340,
},
},
{
id: 17,
title: 'Rain Jacket Women Windbreaker Striped Climbing Raincoats',
price: 39.99,
description:
"Lightweight perfet for trip or casual wear---Long sleeve with hooded, adjustable drawstring waist design. Button and zipper front closure raincoat, fully stripes Lined and The Raincoat has 2 side pockets are a good size to hold all kinds of things, it covers the hips, and the hood is generous but doesn't overdo it.Attached Cotton Lined Hood with Adjustable Drawstrings give it a real styled look.",
category: "women's clothing",
image: 'https://fakestoreapi.com/img/71HblAHs5xL._AC_UY879_-2.jpg',
rating: {
rate: 3.8,
count: 679,
},
},
{
id: 18,
title: "MBJ Women's Solid Short Sleeve Boat Neck V ",
price: 9.85,
description:
'95% RAYON 5% SPANDEX, Made in USA or Imported, Do Not Bleach, Lightweight fabric with great stretch for comfort, Ribbed on sleeves and neckline / Double stitching on bottom hem',
category: "women's clothing",
image: 'https://fakestoreapi.com/img/71z3kpMAYsL._AC_UY879_.jpg',
rating: {
rate: 4.7,
count: 130,
},
},
{
id: 19,
title: "Opna Women's Short Sleeve Moisture",
price: 7.95,
description:
'100% Polyester, Machine wash, 100% cationic polyester interlock, Machine Wash & Pre Shrunk for a Great Fit, Lightweight, roomy and highly breathable with moisture wicking fabric which helps to keep moisture away, Soft Lightweight Fabric with comfortable V-neck collar and a slimmer fit, delivers a sleek, more feminine silhouette and Added Comfort',
category: "women's clothing",
image: 'https://fakestoreapi.com/img/51eg55uWmdL._AC_UX679_.jpg',
rating: {
rate: 4.5,
count: 146,
},
},
{
id: 20,
title: 'DANVOUY Womens T Shirt Casual Cotton Short',
price: 12.99,
description:
'95%Cotton,5%Spandex, Features: Casual, Short Sleeve, Letter Print,V-Neck,Fashion Tees, The fabric is soft and has some stretch., Occasion: Casual/Office/Beach/School/Home/Street. Season: Spring,Summer,Autumn,Winter.',
category: "women's clothing",
image: 'https://fakestoreapi.com/img/61pHAEJ4NML._AC_UX679_.jpg',
rating: {
rate: 3.6,
count: 145,
},
},
];
// 1. function to filter products
// 2. function to find a particular product by title
// 3. function to filter a particular product by title
// 4. function to filter by rating
// 5. reduce this array -> total price
const users = [
{
address: {
geolocation: {
lat: '-37.3159',
long: '81.1496',
},
city: 'kilcoole',
street: 'new road',
number: 7682,
zipcode: '12926-3874',
},
id: 1,
email: 'john@gmail.com',
username: 'johnd',
password: 'm38rmF$',
name: {
firstname: 'john',
lastname: 'doe',
},
phone: '1-570-236-7033',
__v: 0,
},
{
address: {
geolocation: {
lat: '-37.3159',
long: '81.1496',
},
city: 'kilcoole',
street: 'Lovers Ln',
number: 7267,
zipcode: '12926-3874',
},
id: 2,
email: 'morrison@gmail.com',
username: 'mor_2314',
password: '83r5^_',
name: {
firstname: 'david',
lastname: 'morrison',
},
phone: '1-570-236-7033',
__v: 0,
},
{
address: {
geolocation: {
lat: '40.3467',
long: '-30.1310',
},
city: 'Cullman',
street: 'Frances Ct',
number: 86,
zipcode: '29567-1452',
},
id: 3,
email: 'kevin@gmail.com',
username: 'kevinryan',
password: 'kev02937@',
name: {
firstname: 'kevin',
lastname: 'ryan',
},
phone: '1-567-094-1345',
__v: 0,
},
{
address: {
geolocation: {
lat: '50.3467',
long: '-20.1310',
},
city: 'San Antonio',
street: 'Hunters Creek Dr',
number: 6454,
zipcode: '98234-1734',
},
id: 4,
email: 'don@gmail.com',
username: 'donero',
password: 'ewedon',
name: {
firstname: 'don',
lastname: 'romer',
},
phone: '1-765-789-6734',
__v: 0,
},
{
address: {
geolocation: {
lat: '40.3467',
long: '-40.1310',
},
city: 'san Antonio',
street: 'adams St',
number: 245,
zipcode: '80796-1234',
},
id: 5,
email: 'derek@gmail.com',
username: 'derek',
password: 'jklg*_56',
name: {
firstname: 'derek',
lastname: 'powell',
},
phone: '1-956-001-1945',
__v: 0,
},
{
address: {
geolocation: {
lat: '20.1677',
long: '-10.6789',
},
city: 'el paso',
street: 'prospect st',
number: 124,
zipcode: '12346-0456',
},
id: 6,
email: 'david_r@gmail.com',
username: 'david_r',
password: '3478*#54',
name: {
firstname: 'david',
lastname: 'russell',
},
phone: '1-678-345-9856',
__v: 0,
},
{
address: {
geolocation: {
lat: '10.3456',
long: '20.6419',
},
city: 'fresno',
street: 'saddle st',
number: 1342,
zipcode: '96378-0245',
},
id: 7,
email: 'miriam@gmail.com',
username: 'snyder',
password: 'f238&@*$',
name: {
firstname: 'miriam',
lastname: 'snyder',
},
phone: '1-123-943-0563',
__v: 0,
},
{
address: {
geolocation: {
lat: '50.3456',
long: '10.6419',
},
city: 'mesa',
street: 'vally view ln',
number: 1342,
zipcode: '96378-0245',
},
id: 8,
email: 'william@gmail.com',
username: 'hopkins',
password: 'William56$hj',
name: {
firstname: 'william',
lastname: 'hopkins',
},
phone: '1-478-001-0890',
__v: 0,
},
{
address: {
geolocation: {
lat: '40.12456',
long: '20.5419',
},
city: 'miami',
street: 'avondale ave',
number: 345,
zipcode: '96378-0245',
},
id: 9,
email: 'kate@gmail.com',
username: 'kate_h',
password: 'kfejk@*_',
name: {
firstname: 'kate',
lastname: 'hale',
},
phone: '1-678-456-1934',
__v: 0,
},
{
address: {
geolocation: {
lat: '30.24788',
long: '-20.545419',
},
city: 'fort wayne',
street: 'oak lawn ave',
number: 526,
zipcode: '10256-4532',
},
id: 10,
email: 'jimmie@gmail.com',
username: 'jimmie_k',
password: 'klein*#%*',
name: {
firstname: 'jimmie',
lastname: 'klein',
},
phone: '1-104-001-4567',
__v: 0,
},
];
// 1. create a new array, that only has users who have a yahoo email
// 2. create a new array, with users who don't have a '$#^%&*!'
// 3. create a new array, which only has an object that has [{firstName: '', lastName: ''}, {}]
Scratchpad #9
// let product = {
// name: 'iPhone 13',
// brand: 'Apple',
// price: 100000,
// inStock: 300,
// onSale: false,
// tags: ['apple', 'iphone', 'cool'],
// address: { city: 'Mumbai', state: 'Maharastra' },
// };
// console.log(product.price, product.name);
// const movieReviews = [4.5, 5.0, 3.2, 2.1, 4.7, 3.8, 3.1, 3.9, 4.4];
// const highest = Math.max(...movieReviews);
// const lowest = Math.min(...movieReviews);
// let total = 0;
// movieReviews.forEach((rating) => (total += rating));
// const average = total / movieReviews.length;
// const info1 = { highest, lowest, average };
// console.log(info1);
// const getReviewDetails = (arr) => {
// const highest = Math.max(...arr);
// const lowest = Math.min(...arr);
// const total = arr.reduce((accumulator, nextVal) => accumulator + nextVal);
// const average = total / arr.length;
// return {
// highest,
// lowest,
// total: 'Hello World',
// 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);
// console.log(statistics);
// const username = 'janedoe';
// const role = 'admin';
// const user1 = {
// [role]: username,
// };
// // {
// // admin: 'janedoe'
// // }
// console.log(user1);
// const addProperty = (obj, k, v) => {
// return { ...obj, [k]: v };
// };
// const result = addProperty({ name: 'john', age: 25 }, 'job', 'Programmer');
// console.log(result);
// const maths = {
// add: (a, b) => a + b,
// subtract: (a, b) => a - b,
// max: (...nums) => nums.reduce((a, cv) => (cv > a ? cv : a)),
// };
// console.log(maths.add(10, 4));
// console.log(maths.max(345, 34, 1, 2, -3, 43, 34, 1234));
// const math = {
// multiply(x, y) {
// return x * y;
// },
// divide(x, y) {
// return x / y;
// },
// square(x) {
// return x * x;
// },
// };
// console.log(math.square(5));
// function greet() {
// console.log('Hello World!');
// console.log(this);
// }
// function helloWorldBro() {
// console.log("What's up Bro!");
// }
// // greet();
// // helloWorldBro();
// console.log(this);
// let helloWorldBroAgain = 'John Doe is the bro!';
// helloWorldBro();
function greet() {
console.log('Hello World');
console.log(this);
}
// const profile = {
// firstName: 'John',
// lastName: 'Doe',
// age: 25,
// greet() {
// console.log('Hello World');
// console.log(this);
// },
// getAge() {
// // console.log('Hello World');
// console.log(this.age);
// },
// };
// const janeProfile = {
// firstName: 'Jane',
// lastName: 'Doe',
// age: 30,
// getAge()
// }
// greet();
// profile.greet();
// profile.getAge();
// const getAge = profile.getAge;
// getAge();
// profile.getAge();
// 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();
// const user = {
// firstName: 'John',
// lastName: 'Doe',
// role: 'admin',
// fullName() {
// return `${this.firstName} ${this.lastName} is an ${this.role}`;
// },
// logDetails() {
// console.log(`${this.fullName()} and is cool!`);
// },
// };
// user.logDetails();
// console.log(this);
const hellos = {
messages: [
'hello world',
'hello universe',
'hello darkness',
'hello hello',
'heylo',
],
pickMsg() {
const index = Math.floor(Math.random() * this.messages.length);
return this.messages[index];
},
start() {
setInterval(() => {
console.log(this.pickMsg());
}, 1000);
},
};
hellos.start();
// console.log(hellos.pickMsg());
// setInterval(function () {
// console.log('Hello World');
// }, 500);
Scratchpad #10
// const profile = {
// firstName: 'John',
// lastName: 'Doe',
// age: 25,
// introduce: function () {
// console.log(`My name is ${this.firstName} ${this.lastName}`);
// },
// greet: function () {
// setTimeout(() => console.log(this.firstName + ' ' + this.lastName), 3000);
// },
// };
// profile.greet();
// console.log('Hello World');
// console.dir(document.body.children[2]);
// const title = document.getElementById('specialTitle');
// console.dir(title);
// console.log(document.images);
// const username = document.getElementById('username');
// console.log(username);
// const paras = document.getElementsByTagName('p');
// console.log(paras[2]);
// const elms = document.getElementsByClassName('blue')[0];
// console.log(elms);
// const ul = document.getElementsByTagName('ul')[0];
// console.log(ul);
// const li_blues = ul.getElementsByClassName('blue');
// console.log(li_blues);
// // const result = document.querySelector('.blue');
// const result = document.querySelectorAll('.blue');
// console.log(result[1]);
// const title = document.querySelector('h1');
// console.dir(title);
// title.innerText = 'Goodbye World';
// setTimeout(() => {
// title.innerText = 'Goodbye World';
// }, 3000);
// title.innerText = 'This is a title';
// const ul = document.querySelector('ul');
// console.dir(ul.innerText);
// ul.innerText = 'Hello';
// console.log(document.body.innerText);
// console.log(ul.textContent);
// const username = 'johndoe1234';
// const p = document.querySelector('p');
// p.innerHTML = `Hello <i><b>${username}</b></i>`;
// // console.log(p);
// const blueP = document.querySelector('.blue');
// console.log(blueP.innerHTML);
// const input = document.querySelector('input');
// input.value = 'Hello World';
// input.id = 'specialInput';
// const a = document.querySelector('a');
// console.log(a);
// a.href = 'https://u5b.f44.myftpupload.com';
// a.target = '_blank';
// const img = document.querySelector('img');
// setTimeout(() => {
// img.src =
// 'https://4.img-dpreview.com/files/p/E~TS590x0~articles/3925134721/0266554465.jpeg';
// }, 3000);
// console.dir(input);
// const range = document.querySelector('input[type="range"]');
// // console.log(range.getAttribute('hello'));
// range.setAttribute('max', 2000);
// range.setAttribute('class', 'helloworld');
// range.setAttribute('type', 'text');
// const title = document.querySelector('#specialTitle');
// const ul = document.querySelector('ul');
// console.log(title.previousElementSibling);
// console.log(ul.parentElement.parentElement);
// const lis = document.querySelectorAll('li');
// for (let li of lis) {
// li.innerText = 'Hello World';
// }
// const title = document.querySelector('#specialTitle');
// console.log(title.style.color);
// title.style.color = 'green';
// title.style.textDecoration = 'underline';
// title.style.fontSize = '100';
// 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 = 'black';
// li.style.fontFamily = 'Helvetica, sans-serif';
// }
const title = document.querySelector('#specialTitle');
const res = getComputedStyle(title);
console.log(res.color);
Scratchpad #11
// // const todo = document.querySelector('#todos .todo');
// // // todo.style.textDecoration = 'line-through';
// // // todo.style.opacity = 0.5;
// // // todo.style.color = 'red';
// // // todo.setAttribute('class', 'done');
// // // todo.classList.add('done');
// // // todo.classList.remove('todo');
// // todo.classList.toggle('done');
// // // console.log(todo.classList);
// // const h2 = document.createElement('h2');
// // h2.innerText = 'Hello World. This is a subheading.';
// // const section = document.querySelector('section');
// // // section.appendChild(h2);
// // const photo = document.createElement('img');
// // photo.setAttribute(
// // 'src',
// // 'https://previews.123rf.com/images/aquir/aquir1311/aquir131100316/23569861-sample-grunge-red-round-stamp.jpg'
// // );
// // photo.setAttribute('alt', 'A sample image');
// // photo.style.width = '300px';
// // section.appendChild(photo);
// // const card = document.createElement('article');
// // card.style.borderRadius = '5px';
// // card.style.backgroundColor = 'gray';
// // card.style.boxShadow = '1px 1px 2px 0 rgba(0,0,0,0.1)';
// // const img = document.createElement('img');
// // img.setAttribute(
// // 'src',
// // 'https://previews.123rf.com/images/aquir/aquir1311/aquir131100316/23569861-sample-grunge-red-round-stamp.jpg'
// // );
// // img.setAttribute('alt', 'Feature image');
// // img.style.height = '80px';
// // const cardBody = document.createElement('div');
// // cardBody.style.padding = '20px';
// // const title = document.createElement('h4');
// // title.innerText = 'Some important article';
// // title.style.fontSize = '20px';
// // title.style.color = '#333333';
// // const p = document.createElement('p');
// // p.innerText =
// // 'Lorem ipsum dolor sit amet consectetur adipisicing elit. Quia a doloribus labore voluptate pariatur. Fugiat facilis repellendus voluptatem repellat. Labore?';
// // p.style.opacity = '0.7';
// // const a = document.createElement('a');
// // a.setAttribute('href', 'https://u5b.f44.myftpupload.com');
// // a.innerText = 'Read More';
// // cardBody.appendChild(title);
// // cardBody.appendChild(p);
// // cardBody.appendChild(a);
// // card.appendChild(img);
// // card.appendChild(cardBody);
// function addStyles(el, styles) {
// for (let style in styles) {
// el.style[style] = styles[style];
// }
// }
// // const div = document.createElement('div');
// // div.innerText = 'Test content';
// // addStyles(div, {
// // borderRadius: '5px',
// // backgroundColor: 'gray',
// // boxShadow: '1px 1px 2px 0 rgba(0,0,0,0.1)',
// // });
// // const section = document.querySelector('section');
// // section.appendChild(div);
// // function createCard(imgUrl, altText, titleText, description, btnUrl, btnText) {
// // const card = document.createElement('article');
// // // card.style.borderRadius = '5px';
// // // card.style.backgroundColor = 'gray';
// // // card.style.boxShadow = '1px 1px 2px 0 rgba(0,0,0,0.1)';
// // addStyles(card, {
// // borderRadius: '5px',
// // backgroundColor: 'gray',
// // boxShadow: '1px 1px 2px 0 rgba(0,0,0,0.1)',
// // });
// // const img = document.createElement('img');
// // img.setAttribute('src', imgUrl);
// // img.setAttribute('alt', altText);
// // img.style.height = '80px';
// // const cardBody = document.createElement('div');
// // cardBody.style.padding = '20px';
// // const title = document.createElement('h4');
// // title.innerText = titleText;
// // title.style.fontSize = '20px';
// // title.style.color = '#333333';
// // const p = document.createElement('p');
// // p.innerText = description;
// // p.style.opacity = '0.7';
// // const a = document.createElement('a');
// // a.setAttribute('href', btnUrl);
// // a.innerText = btnText;
// // cardBody.appendChild(title);
// // cardBody.appendChild(p);
// // cardBody.appendChild(a);
// // card.appendChild(img);
// // card.appendChild(cardBody);
// // return card;
// // }
// // const card1 = createCard(
// // 'https://images.unsplash.com/photo-1579353977828-2a4eab540b9a?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8c2FtcGxlfGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&w=1000&q=80',
// // 'Sample image',
// // 'This is the first article',
// // 'This is some description text. Hello World.'
// // );
// // const card2 = createCard(
// // 'https://images.unsplash.com/photo-1579353977828-2a4eab540b9a?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8c2FtcGxlfGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&w=1000&q=80',
// // 'Sample image',
// // 'This is the second article',
// // 'This is some description text. Hello Universe.'
// // );
// // const section = document.querySelector('section');
// // section.appendChild(card1);
// // section.appendChild(card2);
// // const todos = document.querySelector('#todos');
// // const newTask = document.createElement('li');
// // newTask.innerText = 'Brand new task to complete';
// // 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);
// // 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);
// // p.prepend(b, i);
// // const todos = document.querySelector('#todos');
// // const firstTask = todos.querySelector('li');
// // const secondTask = firstTask.nextElementSibling;
// // // console.log(firstTask, secondTask);
// // // todos.removeChild(firstTask);
// // // todos.removeChild(secondTask);
// // firstTask.remove();
// // secondTask.remove();
// // const btn1 = document.querySelector('#btn1');
// // btn1.onclick = function () {
// // console.log('I was clicked');
// // };
// // btn1.onclick = function () {
// // console.log('Something else');
// // };
// // btn1.onmouseover = function () {
// // const p = document.createElement('p');
// // p.innerText = 'I was added using JS';
// // document.body.appendChild(p);
// // };
// const btn1 = document.querySelector('#btn1');
// btn1.addEventListener('click', () => {
// console.log('I was clicked');
// alert('Hello World');
// });
// btn1.addEventListener('click', () => {
// console.log('I am also running at the same time');
// });
// btn1.addEventListener('mouseout', () => {
// console.log('I was hovered');
// });
// // document.body.addEventListener('mouseover', () => {
// // alert("What's up!");
// // });
// window.addEventListener('scroll', () => console.log('SCROLLING'));
const btn = document.querySelector('button');
btn.addEventListener('mouseover', () => {
const height = Math.floor(Math.random() * window.innerHeight) + 1;
const width = Math.floor(Math.random() * window.innerWidth) + 1;
btn.style.left = `${width}px`;
btn.style.top = `${height}px`;
});
btn.addEventListener('click', () => console.log('YOU WON!'));
Scratchpad #12
// // const btn = document.querySelector('button');
// // const h1 = document.querySelector('h1');
// // // const handleButtonClick = (event) => {
// // // console.log('I got clicked');
// // // };
// // // btn.addEventListener('click', () => {})
// // btn.addEventListener('click', (e) => console.log(e));
// // const form = document.querySelector('form');
// // form.addEventListener('submit', (event) => {
// // event.preventDefault();
// // });
// // const taskInput = document.querySelector('#task');
// // taskInput.addEventListener('keydown', (e) => console.log('I was pressed'));
// // taskInput.addEventListener('keyup', (e) =>
// // console.log('I just release the key')
// // );
// // taskInput.addEventListener('keypress', (e) => console.log(e));
// // let data = '';
// // const p = document.querySelector('p');
// // taskInput.addEventListener('keypress', (event) => {
// // // console.log(event.target.value);
// // // console.log(event);
// // p.innerText = event.target.value;
// // });
// // const form = document.querySelector('form');
// // const taskInput = document.querySelector('#task');
// // const tasks = document.querySelector('ul');
// // form.addEventListener('submit', (event) => {
// // event.preventDefault();
// // const task = document.createElement('li');
// // task.innerText = taskInput.value;
// // task.addEventListener('click', (event) => {
// // event.target.remove();
// // });
// // tasks.append(task);
// // taskInput.value = '';
// // });
// // const form = document.querySelector('form');
// const taskInput = document.querySelector('#task');
// const tasks = document.querySelector('ul');
// taskInput.addEventListener('keypress', (event) => {
// if (event.key === 'Enter') {
// const task = document.createElement('li');
// task.innerText = taskInput.value;
// task.addEventListener('click', (event) => {
// event.target.remove();
// });
// tasks.append(task);
// taskInput.value = '';
// }
// });
// function message() {
// return 'Hello,';
// }
// function sayName() {
// return `${message()} John`;
// }
// function hello() {
// console.log(`${sayName()}. How are you`);
// }
// hello();
// console.log('First log');
// alert('Some alert. Please close this');
// console.log('Second log');
// console.log('First Log');
// setTimeout(() => console.log('Second log. I took time to complete'), 3000);
// console.log('Third log');
// const btn = document.querySelector('button');
// setTimeout(() => {
// btn.style.transform = `translateX(100px)`;
// setTimeout(() => {
// btn.style.transform = `translateX(200px)`;
// setTimeout(() => {
// btn.style.transform = `translateX(300px)`;
// setTimeout(() => {
// btn.style.transform = `translateX(400px)`;
// setTimeout(() => {
// btn.style.transform = `translateX(500px)`;
// setTimeout(() => {
// btn.style.transform = `translateX(600px)`;
// }, 1000);
// }, 1000);
// }, 1000);
// }, 1000);
// }, 1000);
// }, 1000);
const willGetAPlaystation = new Promise((resolve, reject) => {
const random = Math.random();
if (random > 0.5) {
resolve({ result: 'Success', message: "I'm happy!" });
} else {
reject({ result: 'Fail', message: 'Mai ghar chod dunga' });
}
});
willGetAPlaystation
.then((val) => console.log(val.message))
.catch((err) => console.log(err.message));
Scratchpad #13
// const makePlayStationPromise = () => {
// return new Promise((resolve, reject) => {
// setTimeout(() => {
// const rand = Math.random();
// if (rand < 0.5) {
// resolve();
// } else {
// reject();
// }
// }, 2000);
// });
// };
// const prom = makePlayStationPromise();
// prom
// .then(() => console.log('Promise was successful'))
// .catch(() => {
// console.log('ERROR');
// });
// console.log('This is after the async function above');
// const fakeRequest = (url) => {
// return new Promise((resolve, reject) => {
// setTimeout(() => {
// const pages = {
// '/users': [
// { id: 1, username: 'john' },
// { id: 2, username: 'jane' },
// ],
// '/about': 'This is the about page',
// };
// const data = pages[url];
// if (data) {
// resolve({ status: 200, data });
// } else {
// reject({ status: 404 });
// }
// }, 3000);
// });
// };
// fakeRequest('/users')
// .then((res) => console.log(res.status))
// .catch((err) => console.log(err));
// fakeRequest('/about')
// .then((res) => console.log(res))
// .catch((err) => console.log(err));
// fakeRequest('/contact')
// .then((res) => console.log(res))
// .catch((err) => console.log(err));
// const fakeRequest = (url) => {
// return new Promise((resolve, reject) => {
// setTimeout(() => {
// const pages = {
// '/users': [
// { id: 1, username: 'john' },
// { id: 2, username: 'jane' },
// ],
// '/users/1': {
// id: 1,
// username: 'johndoe',
// topPostId: 53231,
// city: 'mumbai',
// },
// '/users/5': {
// id: 1,
// username: 'janedoe',
// topPostId: 32443,
// city: 'pune',
// },
// '/posts/53231': {
// id: 1,
// title: 'Really amazing post',
// slug: 'really-amazing-post',
// },
// };
// const data = pages[url];
// if (data) {
// resolve({ status: 200, data });
// } else {
// reject({ status: 404 });
// }
// }, 1000);
// });
// };
// fakeRequest('/users')
// .then((response) => {
// console.log(response.data);
// const id = response.data[0].id;
// return fakeRequest(`/users/${id}`);
// })
// .then((response) => {
// console.log(response.data);
// const topPostId = response.data.topPostId;
// return fakeRequest(`/posts/${topPostId}`);
// })
// .then((response) => console.log(response.data))
// .catch((error) => console.log(error));
// const req = new XMLHttpRequest();
// req.onload = function () {
// const data = JSON.parse(this.responseText);
// console.log(data);
// };
// req.onerror = function (err) {
// console.log('This was the error', err);
// };
// req.open('get', 'https://swapi.dev/api/people/1', true);
// req.setRequestHeader('Accept', 'application/json');
// req.send();
// fetch('https://swapi.dev/api/planets')
// .then((response) => {
// // console.log(response);
// if (response.ok) {
// return response.json();
// } else {
// throw new Error();
// }
// })
// .then((data) => console.log(data))
// .catch((err) => {
// console.log(err);
// });
// console.log(axios);
// axios
// .get('https://swapi.dev/api/planets/1')
// .then((response) => {
// const resident = response.data.residents[0];
// return axios.get(resident);
// })
// .then((response) => console.log(response))
// .catch((err) => console.log(err));
// const section = document.querySelector('section');
// axios
// .get('https://swapi.dev/api/planets')
// .then((response) => {
// const planets = response.data.results;
// for (let planet of planets) {
// const planetCard = document.createElement('article');
// planetCard.classList.add('planet-card');
// const planetName = document.createElement('p');
// planetName.innerText = planet.name;
// const planetMetaData = document.createElement('div');
// planetMetaData.innerHTML = `<span>CLIMATE: ${planet.climate}</span><br /><span>DIAMETER: ${planet.diameter}</span>`;
// planetCard.append(planetName, planetMetaData);
// section.append(planetCard);
// }
// })
// .catch((err) => console.log(err));
// axios
// .get('https://swapi.dev/api/starships/9/')
// .then((res) => {
// const film = res.data.films[0];
// return axios.get(film);
// })
// .then((res) => console.log(res))
// .catch((err) => console.log(err));
Scratchpad #14
// function getData() {
// const data = axios.get('https://swapi.dev/api/planets');
// // console.log(data); // Promise {<pending>}
// data
// .then((res) => {
// console.log(res.data);
// })
// .catch((err) => console.log(err));
// }
// getData();
// async function greet() {
// return 'hello!';
// }
// greet().then((data) => console.log(data));
// function add(x, y) {
// return new Promise((resolve, reject) => {
// if (typeof x !== 'number' || typeof y !== 'number') {
// reject('X and Y must be numbers');
// }
// resolve(x + y);
// });
// }
// async function add(x, y) {
// if (typeof x !== 'number' || typeof y !== 'number') {
// throw new Error('X and Y must be numbers');
// }
// return x + y;
// }
// add(10, 20)
// .then((res) => console.log(res))
// .catch((err) => console.log(err));
// function getPlanets() {
// return axios.get('https://swapi.dev/api/planets');
// }
// getPlanets().then((res) => {
// console.log(res.data);
// });
// function getPlanets() {
// const data = axios.get('https://swapi.dev/api/planets');
// data.then((res) => console.log(res.data));
// }
// getPlanets();
// async function getPlanets() {
// const { data } = await axios.get('https://swapi.dev/api/planets');
// console.log(data.results);
// }
// // getPlanets().catch((err) => console.log(err));
// getPlanets();
// async function getPlanets() {
// try {
// const { data } = await axios.get('https://swapi.dev/api/planets');
// console.log(data.results);
// } catch (err) {
// console.log(err);
// }
// }
// // getPlanets();
// async function getPokemon() {
// const pokemon1Promise = axios.get('https://pokeapi.co/api/v2/pokemon/1');
// const pokemon2Promise = axios.get('https://pokeapi.co/api/v2/pokemon/1');
// const pokemon3Promise = axios.get('https://pokeapi.co/api/v2/pokemon/1');
// // const pokemon1 = await pokemon1Promise;
// // const pokemon2 = await pokemon2Promise;
// // const pokemon3 = await pokemon3Promise;
// const results = await Promise.all([
// pokemon1Promise,
// pokemon2Promise,
// pokemon3Promise,
// ]);
// // console.log(pokemon1.data);
// // console.log(pokemon2.data);
// // console.log(pokemon3.data);
// console.log(results);
// }
// 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 drawnCards = [];
// const deck = initializeDeck();
// shuffle(deck);
// drawCard(deck, drawnCards);
// drawMultiple(5, deck, drawnCards);
// console.log(deck.length, drawnCards);
// 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 deck = makeDeck();
// // console.log(deck);
// // deck.initializeDeck();
// // // console.log(deck);
// // deck.shuffle();
// // deck.drawMultiple(10);
// // console.log(deck);
// const deck1 = makeDeck();
// const deck2 = makeDeck();
// console.log(deck1);
// console.log(deck2);
// 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 john = new Person('John', 'Doe', 25);
// const jack = new Person('Jack', 'Doe', 30);
// console.log(john);
// console.log(jack);
// john.sayName();
// class Person {
// constructor(firstName, lastName, age) {
// this.firstName = firstName;
// this.lastName = lastName;
// this.age = age;
// }
// sayName() {
// console.log(`My name is ${this.firstName} ${this.lastName}`);
// }
// }
// const john = new Person('John', 'Doe', 25);
// const jack = new Person('Jack', 'Doe', 30);
// console.log(john);
// console.log(jack);
// class Deck {
// constructor() {
// this.deck = [];
// this.drawnCards = [];
// this.suits = ['hearts', 'diamonds', 'spades', 'clubs'];
// this.values = '2,3,4,5,6,7,8,9,10,J,Q,K,A';
// }
// initializeDeck() {
// const { suits, values, deck } = this;
// for (let value of values.split(',')) {
// for (let suit of suits) {
// deck.push({ value, suit });
// }
// }
// return deck;
// }
// drawCard() {
// const card = this.deck.pop();
// this.drawnCards.push(card);
// return card;
// }
// drawMultiple(numCards) {
// const cards = [];
// for (let i = 0; i < numCards; i++) {
// cards.push(this.drawCard());
// }
// return cards;
// }
// shuffle() {
// const { deck } = this;
// for (let i = deck.length - 1; i > 0; i--) {
// let j = Math.floor(Math.random() * (i + 1));
// [deck[i], deck[j]] = [deck[j], deck[i]];
// }
// }
// }
// const deck1 = new Deck();
// deck1.initializeDeck();
// deck1.shuffle();
// const deck2 = new Deck();
// deck2.initializeDeck();
// console.log(deck1);
// console.log(deck2);
class User {
constructor(username, password) {
this.username = username;
this.password = password;
}
login(pass) {
if (pass === this.password) {
console.log('Welcome back');
} else {
console.log('Incorrect password entered.');
}
}
}
class Subscriber extends User {
logout() {
console.log('You have successfully logged out, Subscriber');
}
}
class Creator extends User {
constructor(username, password, totalVideos = 0) {
super(username, password);
this.totalVideos = totalVideos;
}
uploadVideo(videoName) {
this.totalVideos++;
console.log(
`Thank you for uploading ${videoName}.\nChannel: ${this.totalVideos} video(s)`
);
}
logout() {
console.log('You have successfully logged out, Creator');
}
}
const user1 = new Subscriber('johndoe', 'doe123');
const user2 = new Creator('janedoe', 'jane123');
user1.login('doe123');
user2.login('asdasd');
user2.uploadVideo('New Song');
console.log(user1);
console.log(user2);
React
<!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 src="https://unpkg.com/prop-types@^15/prop-types.js"></script>
<script type="text/babel">
// const title = document.createElement('h1');
// title.innerText = 'Hello World from the DOM';
// title.classList.add('special-title');
// const root = document.querySelector('#root');
// root.append(title);
// const title = React.createElement('h1', {
// className: 'special-title',
// children: 'Hello World from ReactJS',
// });
// const para = React.createElement('p', {}, 'I am rendered using React JS');
// const div = React.createElement('div', {
// children: [title, para],
// });
// const title = React.createElement('h1', {
// className: 'special-title',
// children: 'Hello World from ReactJS',
// });
// const title = (
// <h1 className='special-title'>Hello World from ReactJS (JSX)</h1>
// );
// const para = <p>I am a paragraph</p>;
// const para = <p children='I am a paragraph' />;
// const children = 'Hello World. This is the page title';
// const className = 'title';
// const props = { children, className };
// const para = <p {...props} />;
// const para = <p className={className}>{children}</p>;
function message(props) {
return (
<div className='helloworld'>
<p className='message'>{props.children}</p>
</div>
);
}
// const element = (
// <div>
// {message({
// children:
// 'Hello World. I am rendering inside the message component.',
// })}
// </div>
// );
// function blogPost(props) {
// return (
// <article className='post'>
// <img src={props.imageUrl} alt={props.imageAlt} />
// <h4>{props.title}</h4>
// <p>{props.children}</p>
// </article>
// );
// }
// function BlogPost(props) {
// return (
// <article className='post'>
// <img src={props.imageUrl} alt={props.imageAlt} />
// <h4>{props.title}</h4>
// <p>{props.children}</p>
// </article>
// );
// }
// function BlogPost({ imageUrl, imageAlt, title, children }) {
// return (
// <article className='post'>
// <img src={imageUrl} alt={imageAlt} />
// <h4>{title}</h4>
// <p>{children}</p>
// </article>
// );
// }
// BlogPost.propTypes = {
// imageUrl: PropTypes.string.isRequired,
// imageAlt: PropTypes.string,
// title: PropTypes.string.isRequired,
// children: PropTypes.string,
// };
// const blogPostEl = React.createElement(blogPost, {
// imageUrl:
// 'https://image.shutterstock.com/image-vector/sample-stamp-square-grunge-sign-260nw-1474408826.jpg',
// imageAlt: 'Some Image',
// title: 'Blog Post #1',
// children:
// 'Lorem ipsum, dolor sit amet consectetur adipisicing elit. Laboriosam sit nam fugiat voluptatum consequuntur aspernatur ab praesentium, delectus animi nobis.',
// });
// React.createElement('p', {}, 'Hello World')
// <p>Hello World</p>
// const element = (
// <div>
// <BlogPost
// imageUrl='https://image.shutterstock.com/image-vector/sample-stamp-square-grunge-sign-260nw-1474408826.jpg'
// imageAlt='Some Image'
// title='Blog Post #222'
// >
// Lorem ipsum, dolor sit amet consectetur adipisicing elit. Laboriosam
// sit nam fugiat voluptatum consequuntur aspernatur ab praesentium,
// delectus animi nobis.
// </BlogPost>
// <BlogPost imageAlt='Some Image'>
// Lorem ipsum, dolor sit amet consectetur adipisicing elit. Laboriosam
// sit nam fugiat voluptatum consequuntur aspernatur ab praesentium,
// delectus animi nobis.
// </BlogPost>
// </div>
// );
ReactDOM.render(element, document.querySelector('#root'));
</script>
</body>
</html>