feat(Complete JavaScript): All JS concepts

pull/763/head
tush-tr 3 years ago
parent b07e06e1a4
commit 2466085c95

File diff suppressed because it is too large Load Diff

@ -0,0 +1,9 @@
let movies = [
"Badrinath ki dulhaniya",
"The amazing spider man",
"Jatt james bond"
]
const movie = movies.find(movie=>{
return movie.includes('Th')
})
console.log(movie);

@ -0,0 +1,28 @@
const nums = [2,3,4,5,6,6];
nums.forEach((e)=>{
console.log(e);
})
// add 2 in every element of the array
let arr = []
nums.forEach((e)=>{
arr.push(e*2)
})
console.log(arr)
let cars = [
{
"color": "purple",
"type": "minivan",
"registration": new Date('2017-01-03'),
"capacity": 7
},
{
"color": "red",
"type": "station wagon",
"registration": new Date('2018-03-03'),
"capacity": 5
}
]
cars.forEach((car)=>{
console.log(car.color);
})

@ -0,0 +1,21 @@
const arr = [12,3,5,6,7];
const newarr = arr.map((e)=>{
return e*2;
})
console.log(newarr);
const everOddArr = arr.map((n)=>{
return{
value: n,
isEven: n%2===0
}
})
console.log(everOddArr);
/*
[ { value: 12, isEven: true },
{ value: 3, isEven: false },
{ value: 5, isEven: false },
{ value: 6, isEven: true },
{ value: 7, isEven: false } ]
*/

@ -0,0 +1,9 @@
const arr = [2,3,4,5];
// 5- [5,4,5]
// 9- [9,5]
// 14- 14
const sum = arr.reduce((t,c)=>{
return t+c
})
console.log(sum);

@ -0,0 +1,9 @@
const max = (arr)=>{
return arr.reduce((max,curr)=>{
if(curr>max){
return curr;
}
return max;
})
}
console.log(max([12,23,5,64,23]))

@ -0,0 +1,84 @@
const books = [{
title: 'Good Omens',
authors: ['Terry Pratchett', 'Neil Gaiman'],
rating: 4.25,
genres: ['fiction', 'fantasy']
},
{
title: 'Changing My Mind',
authors: ['Zadie Smith'],
rating: 3.83,
genres: ['nonfiction', 'essays']
},
{
title: 'Bone: The Complete Edition',
authors: ['Jeff Smith'],
rating: 4.42,
genres: ['fiction', 'graphic novel', 'fantasy']
},
{
title: 'American Gods',
authors: ['Neil Gaiman'],
rating: 4.11,
genres: ['fiction', 'fantasy']
},
{
title: 'A Gentleman in Moscow',
authors: ['Amor Towles'],
rating: 4.36,
genres: ['fiction', 'historical fiction']
},
{
title: 'The Name of the Wind',
authors: ['Patrick Rothfuss'],
rating: 4.54,
genres: ['fiction', 'fantasy']
},
{
title: 'The Overstory',
authors: ['Richard Powers'],
rating: 4.19,
genres: ['fiction', 'short stories']
},
{
title: 'A Truly Horrible Book',
authors: ['Xavier Time'],
rating: 2.18,
genres: ['fiction', 'garbage']
},
{
title: 'The Way of Kings',
authors: ['Brandon Sanderson'],
rating: 4.65,
genres: ['fantasy', 'epic']
},
{
title: 'Lord of the flies',
authors: ['William Golding'],
rating: 3.67,
genres: ['fiction']
}
]
const groupedByRatings = books.reduce((groupedBooks, book)=>{
let key = Math.floor(book.rating);
if(!groupedBooks[key]){
groupedBooks[key]=[];
}
groupedBooks[key].push(book);
return groupedBooks;
},{})
console.log(groupedByRatings)
// {
// 2:[]
// 3:[]
// 4:[]
// }

@ -0,0 +1,7 @@
let fruits = ['mango','grapes'];
let groc = ['corn flakes','milk']
let shopList = fruits.concat(groc);
let others = ['apple','coffee'];
console.log(shopList); // ['mango','grapes','corn flakes','milk']
shopList = fruits.concat(groc,others);
console.log(shopList);

@ -0,0 +1,8 @@
let ar = [1,2,3,5];
if(ar.includes(10)){ // false
console.log(ar.indexOf(10));
}
else{
console.log(ar.indexOf(2));
}
// output - 1

@ -0,0 +1,11 @@
let arr = [1,2,3,4,5];
arr.reverse()
console.log(arr); // [ 5, 4, 3, 2, 1 ]
let names = ["Tushar","Rahul","Mohan"]
let join1 = names.join()
let join2 = names.join(' ')
let join3 = names.join("&")
console.log(join1) // Tushar,Rahul,Mohan
console.log(join2) // Tushar Rahul Mohan
console.log(join3) // Tushar&Rahul&Mohan

@ -0,0 +1,5 @@
let arr = [1,2,3,4,5,6]
arr.push(7);
console.log(arr); // [1, 2, 3, 4, 5, 6, 7 ]
arr.pop();
console.log(arr) // [ 1, 2, 3, 4, 5, 6 ]

@ -0,0 +1,5 @@
let arr = [12,39,45]
arr.shift()
console.log(arr); // [ 39, 45 ]
arr.unshift(12)
console.log(arr); // [ 12, 39, 45 ]

@ -0,0 +1,5 @@
let watches = ['rolex','rado','apple','mi'];
let expensiveWatches = watches.slice(0,2);
console.log(expensiveWatches) // [ 'rolex', 'rado' ]
let expensiveDigitalWatches = watches.slice(2);
console.log(expensiveDigitalWatches)

@ -0,0 +1,3 @@
let arr = [1,24,54,6,3,53,3,55,65];
arr.sort()
console.log(arr)

@ -0,0 +1,6 @@
let arr = [1,2,3,4,5,6];
// let arrDeletedItems = arr.splice(start[, deleteCount[, item1[, item2[, ...]]]])
arr.splice(1,0,15);
console.log(arr); // [ 1, 15, 2, 3, 4, 5, 6 ]
arr.splice(2,2);
console.log(arr); // [1, 15, 4, 5, 6 ]

@ -0,0 +1,16 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>AXIOS DOCUMENT</h1>
<button>HI!!</button>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="script1.js"></script>
<!-- <script src="script2.js"></script> -->
</body>
</html>

@ -0,0 +1,211 @@
console.log("Helo")
// async function getData(){
// // if I want to request 3 urls
// const res = await axios.get("https://pokeapi.co/api/v2/pokemon/1")
// const res2 = await axios.get("https://pokeapi.co/api/v2/pokemon/2")
// const res3 = await axios.get("https://pokeapi.co/api/v2/pokemon/3")
// console.log(res.data)
// }
// async function getData(){
// // if I want to request 3 urls
// const res = axios.get("https://pokeapi.co/api/v2/pokemon/1")
// const res2 = axios.get("https://pokeapi.co/api/v2/pokemon/2")
// const res3 = axios.get("https://pokeapi.co/api/v2/pokemon/3")
// const poke1 = await res
// const poke2 = await res2
// const poke3 = await res3
// // now res, res2, res3 are promises not data
// console.log(poke1.data)
// }
async function getData(){
const res = axios.get("https://pokeapi.co/api/v2/pokemon/1")
const res2 = axios.get("https://pokeapi.co/api/v2/pokemon/2")
const res3 = axios.get("https://pokeapi.co/api/v2/pokemon/3")
const results = await Promise.all([res,res2,res3])
console.log(results)
}
getData()
// async function hello(){
// return "Hey Guys"
// }
// hello().then((value) => {
// console.log(value)
// })
// const add = async (a,b) => {
// if(typeof(a)!== 'number' | typeof(b)!== 'number' ){
// throw new Error("Not a number")
// }
// return a+b;
// }
// add(24,35).then((value) => {console.log(value)})
// async function getData(){
// try{
// const res = await axios.get('https://swapi.dev/api/planets')
// console.log(res.data)
// }
// catch(err){
// console.log(err)
// }
// }
// getData()
// getData().catch((err) => {console.log(err)})
// --_________________________
// const moveX = (element, amount, delay) => {
// return new Promise((resolve, reject) => {
// setTimeout(() => {
// const bodyBoundary = document.body.clientWidth;
// const elRight = element.getBoundingClientRect().right;
// const currLeft = element.getBoundingClientRect().left;
// if (elRight + amount > bodyBoundary) {
// reject({ bodyBoundary, elRight, amount });
// }
// else {
// element.style.transform = `translateX(${currLeft + amount}px)`;
// resolve();
// }
// }, delay);
// });
// };
// const btn = document.querySelector('button');
// async function animateRight(el, amt) {
// await moveX(el, amt, 1000);
// await moveX(el, amt, 1000);
// await moveX(el, amt, 1000);
// await moveX(el, amt, 1000);
// await moveX(el, amt, 1000);
// await moveX(el, amt, 1000);
// await moveX(el, amt, 1000);
// await moveX(el, amt, 1000);
// await moveX(el, amt, 1000);
// await moveX(el, amt, 1000);
// }
// animateRight(btn, 100).catch((err) => {
// console.log('Hit the right edge! Now Moving left!');
// animateRight(btn, -100);
// });
// const btn = document.querySelector('button');
// moveX(btn, 100, 1000)
// .then(() => moveX(btn, 100, 1000))
// .then(() => moveX(btn, 100, 1000))
// .then(() => moveX(btn, 100, 1000))
// .then(() => moveX(btn, 100, 1000))
// .then(() => moveX(btn, 100, 1000))
// .then(() => moveX(btn, 100, 1000))
// .then(() => moveX(btn, 100, 1000))
// .then(() => moveX(btn, 100, 1000))
// .then(() => moveX(btn, 100, 1000))
// .then(() => moveX(btn, 100, 1000))
// .then(() => moveX(btn, 100, 1000))
// .then(() => moveX(btn, 100, 1000))
// .then(() => moveX(btn, 100, 1000))
// .then(() => moveX(btn, 100, 1000))
// .then(() => moveX(btn, 100, 1000))
// .catch(({ bodyBoundary, amount, elRight }) => {
// console.log(`Cannot Move! Body is ${bodyBoundary}px wide`);
// console.log(`Element is at ${elRight}px, ${amount}px is too large!`);
// });
//This function moves an element "amount" number of pixels after a delay.
//If the element will stay on screen, we move the element and call the onSuccess callback function
//If the element will move off screen, we do not move the element and instead call the onFailure callback
// const moveX = (element, amount, delay, onSuccess, onFailure) => {
// setTimeout(() => {
// const bodyBoundary = document.body.clientWidth;
// const elRight = element.getBoundingClientRect().right;
// const currLeft = element.getBoundingClientRect().left;
// if (elRight + amount > bodyBoundary) {
// onFailure();
// }
// else {
// element.style.transform = `translateX(${currLeft + amount}px)`;
// onSuccess();
// }
// }, delay);
// };
// LOOK AT THIS UGLY MESS!
// moveX(
// btn,
// 300,
// 1000,
// () => {
// //success callback
// moveX(
// btn,
// 300,
// 1000,
// () => {
// //success callback
// moveX(
// btn,
// 300,
// 1000,
// () => {
// //success callback
// moveX(
// btn,
// 300,
// 1000,
// () => {
// //success callback
// moveX(
// btn,
// 300,
// 1000,
// () => {
// //success callback
// alert('YOU HAVE A WIDE SCREEN!');
// },
// () => {
// //failure callback
// alert('CANNOT MOVE FURTHER!');
// }
// );
// },
// () => {
// //failure callback
// alert('CANNOT MOVE FURTHER!');
// }
// );
// },
// () => {
// //failure callback
// alert('CANNOT MOVE FURTHER!');
// }
// );
// },
// () => {
// //failure callback
// alert('CANNOT MOVE FURTHER!');
// }
// );
// },
// () => {
// //failure callback
// alert('CANNOT MOVE FURTHER!');
// }
// );

@ -0,0 +1,30 @@
const repeat = (str, times) => {
let result = '';
for (let i = 0; i < times; i++)
{
result += str;
}
return result;
};
const scream = (str) => {
return str.toUpperCase() + '!!!';
};
const getRantText = (phrase) => {
let text = scream(phrase);
let rant = repeat(text, 8);
return rant;
};
const makeRant = (phrase, el) => {
const h1 = document.createElement('h1');
h1.innerText = getRantText(phrase);
el.appendChild(h1);
};
console.log('HELLO!');
makeRant('I hate mayonnaise', document.body);
makeRant('if you have to cough, please cover your mouth', document.body);

@ -0,0 +1,27 @@
const btn = document.querySelector('button');
// setTimeout(() => {
// btn.style.transform = `translateX(100px)`;
// setTimeout(() => {
// btn.style.transform = `translateX(200px)`;
// setTimeout(() => {
// btn.style.transform = `translateX(100px)`;
// setTimeout(() => {
// btn.style.transform = `translateX(100px)`
// }, 1000);
// }, 1000);
// }, 2000);
// }, 3000);
const moveX = (element,amount,delay, callback)=>{
setTimeout(() => {
element.style.transform = `translateX(${amount}px)`;
if(callback){
callback();
}
}, delay);
}
moveX(btn,300,2000,()=>{
moveX(btn,200,1000)
})

@ -0,0 +1,15 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button>Move me</button>
<!-- <script src="call-stack.js"></script> -->
<script src="callbackhell.js"></script>
</body>
</html>

@ -0,0 +1,62 @@
const fakeRequest = (url) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
const pages = {
'/users': [
{ id: 1, username: 'Tushar' },
{ id: 5, username: 'Rahul' }
],
'/users/1': {
id: 1,
username: 'Tushar',
country: 'India',
work: 'Noida',
role: 'Software Engineer',
postid: 54
},
'/users/5': {
id: 5,
username: 'Rahul',
country: 'India',
work: 'Noida',
role: 'DevOps Engineer'
},
'/posts/54': {
id: 54,
title: 'My new Post',
},
'/about': "About page"
}
const data = pages[url]
if (data) {
resolve(pages[url])
}
else {
reject({ status: 400 })
}
}, 2000)
})
}
// fakeRequest('/users').then((data)=>{
// let id = data[0].id;
// fakeRequest(`/users/${id}`).then((data)=>{
// console.log(data)
// })
// })
fakeRequest('/users').then((data) => {
let id = data[0].id;
return fakeRequest(`/users/${id}`)
})
.then((data) => {
// console.log(data)
let postid = data.postid;
return fakeRequest(`/posts/${postid}`)
})
.then((data) => {
console.log(data)
})
.catch((err) => { console.log(err) })

@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- <script src="script.js"></script> -->
<script src="chain.js"></script>
</body>
</html>

@ -0,0 +1,22 @@
const fakeRequest = (url)=>{
return new Promise((resolve,reject)=>{
setTimeout(()=>{
const pages = {
'/users' : "Users pages",
'/about' : "About page"
}
const data = pages[url]
if(data){
resolve(pages[url])
}
else{
reject({status:400})
}
},2000)
})
}
fakeRequest().then((data)=>{
console.log(data)
}).catch((res)=>{console.log(res.status)})

@ -0,0 +1,34 @@
// const willGetYouDog = new Promise((resolve,reject)=>{
// const rand = Math.random();
// if(rand<0.5){
// resolve()
// }
// else
// reject()
// })
// willGetYouDog.then(()=>{
// console.log('DOGGGG')
// }).catch((err)=>{console.log(err)})
const makeDogPromise = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
const rand = Math.random();
if (rand < 0.5) {
resolve()
}
else
reject()
}, 5000)
})
}
// willGetYouDog.then(() => {
// console.log('DOGGGG')
// }).catch((err) => { console.log(err) })
const pro = makeDogPromise()
pro.then(()=>{
console.log("hello")
})

@ -0,0 +1,24 @@
h1 {
color: purple;
font-size: 60px;
}
#bear-photo {
width: 250px;
}
.special {
color: teal;
font-size: 30px;
border: 1px solid teal;
}
input[type="password"] {
height: 50px;
width: 100px;
}
.done{
color:gray;
text-decoration: line-through;
opacity: 50%;
}

@ -0,0 +1,70 @@
// ****************
// querySelector
// ****************
//To find the first li on the page:
document.querySelector('li');
//To find the first element with class of special:
document.querySelector('.special');
//To find the first element with id of main (there should only be one...)
document.querySelector('#main');
// To find the first li with the class of special, nested inside of a ul, nested inside a section:
document.querySelector('section ul li.special');
// ****************
// querySelectorAll
// ****************
// To find ALL li's on the page:
document.querySelectorAll('li');
// To find ALL elements with the class of special on the page:
document.querySelectorAll('.special');
const newElement = (outer, inner, outerClass, innerClass, outerText, innerText)=>{
let e1 = document.createElement(outer)
let e2 = document.createElement(inner)
e1.className = outerClass;
e2.className = innerClass;
e2.innerText = innerText;
e1.innerText = outerText;
e1.appendChild(e2);
return e1;
}
// let el = document.createElement("button");
// let e = document.createElement("li");
// e.className = "todo";
// e.appendChild(el)
console.log(newElement("li","button",'todo','bt','any','X'))
// manipulating class
// const todo = document.querySelector('#todos .todo')
const todos = document.querySelector("#todos")
const todoInput = document.querySelector(".todoinput")
const todoAdd = document.querySelector(".todoadd");
todoAdd.addEventListener("click",()=>{
let value = todoInput.value;
// let node = document.createElement("li");
// let textnode = document.createTextNode()
let newCreatedElement = newElement("li","button",'todo','bt',value,'X')
todos.appendChild(newCreatedElement)
// todos.innerHTML+= `<li class="todo">${value} <button>X</button> </li>`;
})
let buttonTodo = document.querySelectorAll("#todos .todo button")
buttonTodo.forEach((e)=>{
e.addEventListener("click",()=>{
let todo = e.parentElement;
todo.setAttribute("class","done")
})
})
// todo.style.color = 'gray';
// todo.style.textDecoration = 'line-through';
// todo.style.opacity = '50%';

@ -0,0 +1,5 @@
const url = 'https://cdn.vox-cdn.com/thumbor/FxBr6MiQn3W2bWPBA1dQqLvNREQ=/0x0:2040x1360/920x613/filters:focal(857x517:1183x843):format(webp)/cdn.vox-cdn.com/uploads/chorus_image/image/61520649/jbareham_180424_2499_0007.0.jpg'
const section = document.querySelector('section')
const newImg = document.createElement('img')
newImg.setAttribute('src',url)
section.appendChild(newImg)

@ -0,0 +1,71 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>querySelector</title>
<link rel="stylesheet" href="app.css">
</head>
<body>
<h1 class="header">My Webpage</h1>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptas sint natus nostrum quas laudantium quasi ut
voluptatem fugiat aliquid architecto. In distinctio expedita doloribus veritatis, vitae voluptates optio commodi
itaque.
<i>Hell</i>
</p>
<p id="main">Lorem ipsum dolor sit amet consectetur adipisicing elit. Doloribus sint, magni dolorum sapiente voluptate
quia
praesentium autem! Veniam delectus, placeat excepturi in porro minima quo laudantium temporibus, aliquid repellendus
similique.
</p>
<form action="">
<input type="text" placeholder="Bear Name">
<input type="password" placeholder="password">
<input type="submit">
</form>
<p class="special">
ADIJAKLSJDLKSAJLDKJL
</p>
<ul>
<li class="special">First Thing</li>
<li>Second Thing</li>
<li class="special">Third Thing</li>
</ul>
<img id="bear-photo"
src="https://images.unsplash.com/photo-1573920111312-04f1b25c6b85?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1268&q=80"
alt="">
<section>
<ul>
<li>Carrots</li>
<li class="special">Peas</li>
<li>Broccoli</li>
</ul>
</section>
<section>
<button class="btn">1</button><button class="btn">2</button><button class="btn"></button><button class="btn"></button><button class="btn"></button><button class="btn"></button><button class="btn"></button><button class="btn"></button><button class="btn"></button><button class="btn"></button>
<script>
const btns = document.querySelectorAll(".btn");
btns.forEach(element => {
element.innerText = "Butt"
});
</script>
</section>
<h3>TODO List</h3>
<input type="text" class="todoinput">
<button class="todoadd">Add</button>
<ul id="todos">
<li class="todo">Mow the lawn <button>X</button> </li>
<li class="todo">Milk the cows <button>X</button> </li>
<li class="todo">Feed the alpacas <button>X</button> </li>
</ul>
<!-- <script src="app.js" ></script> -->
<!-- <script src="create-elements.js" ></script> -->
<script src="remove.js"></script>
</body>
</html>

@ -0,0 +1,3 @@
const ul = document.querySelector('ul')
const removeMe = ul.querySelector('.special')
ul.removeChild(removeMe)

@ -0,0 +1,13 @@
// write a function to find the average value in an array of numbers.
// avg([0,50]) // 25
function avg(arr){
const l = arr.length;
// for(let i =0;i<l;i++){
// sum+=arr[i];
// }
const sum = arr.reduce((total,num)=>{
return total+num;
})
return sum/l;
}
console.log(avg([0,50]));

@ -0,0 +1,4 @@
function diceRoll(){
let roll = Math.floor(Math.random()*6)+1;
console.log(roll);
}

@ -0,0 +1,10 @@
function callTwice(func){
func();
func();
}
function laugh(){
console.log("hahahahahhah");
}
callTwice(laugh);

@ -0,0 +1,49 @@
/*
write a getCard() function which returns a random playing card object, like
{
value: 'K',
suit: 'clubs'
}
pick a random value from
-- 1,2,3,4,5,6,7,8,9,10,J,Q,K,A
pick a random quit from
clubs, spades, hearts, diamonds
return both in an object
*/
function getCard(){
let value;
let randNum = Math.floor(Math.random()*14)+1;
if(randNum===11){
value = 'J';
}
else if(randNum===12){
value = 'Q';
}
else if(randNum===13){
value = 'K';
}
else if(randNum===14){
value = 'A';
}
else{
value = randNum;
}
let suit;
let randSuit = Math.floor(Math.random()*4)+1;
switch(randSuit){
case 1:
suit= 'clubs';
break;
case 2:
suit = 'spades';
break;
case 3:
suit = 'hearts';
break;
case 4:
suit = 'diamonds';
break;
}
return {value: value,suit: suit}
}
console.log(getCard())

@ -0,0 +1,28 @@
function add(x,y){
return x+y;
}
const subtract = function(x,y){
return x-y;
}
function multiply(x,y){
return x*y;
}
const divide = function(x,y){
return x/y;
}
// let's add all these functions to an array
const operations = [add,subtract,multiply,divide];
// now we can use this array of functions like this:
// console.log(operations[0](3,4)) //7
for(let func of operations){
console.log(func(12,34));
}
// now I can also add these functions into an object and create a method
const thing = {
doSomething: multiply
}
// now I can call and use this function as a method of object
console.log(thing.doSomething(23,3));

@ -0,0 +1,7 @@
function makeBetweenFunc(min,max){
return function (val){
return val>=min && val<=max;
}
}
const inAgeRange = makeBetweenFunc(18,100);
console.log(inAgeRange(45));

@ -0,0 +1,20 @@
function add(x,y){
return x+y;
}
const subtract = function(x,y){
return x-y;
}
function multiply(x,y){
return x*y;
}
const divide = function(x,y){
return x/y;
}
function operations(oper,x,y){
return oper(x,y);
}
console.log(operations(add,2,3)); // 5
console.log(operations((a,b)=>{
return a+b;
},45,5)); // 50

@ -0,0 +1,14 @@
/*
a pangram is a sentence that contains every letter of the alphabet,
write a function called isPangram, which checks to see if a given sentence contains every letter of the alphabet.
*/
function isPangram(sentence){
sentence = sentence.toLowerCase();
for(let char of 'abcdefghijklmnopqrstuvwxyz'){
if(sentence.indexOf(char)===-1){
return false;
}
}
return true;
}
console.log(isPangram('Sphinx of black quartz, judge my vow.'))

@ -0,0 +1,22 @@
/*
write a isValidPassword function.
accepts two arguments: password and username
password must:
- be at least 8 characters
- can't contain spaces
- can't contain the username
if all requirements are met, return true, otherwise false
isValidPassword('89Fjjlnms','dogluvr'); // true
*/
function isValidPassword(password, username){
const tooShort = password.length<8;
const containspace = password.indexOf(' ')!==-1;
const containusername = password.indexOf(username)!== -1;
if(tooShort || containspace || containusername){
return false;
}
return true;
}

@ -0,0 +1,9 @@
function multiplyBy(num){
return function(a){ // anonymous function
return a*num;
}
}
const triple = multiplyBy(3);
console.log(triple(20)); // 60
console.log(multiplyBy(3)(20)); // 60

@ -0,0 +1,16 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>AXIOS DOCUMENT</h1>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="script.js"></script>
<!-- <script src="script2.js"></script> -->
</body>
</html>

@ -0,0 +1,20 @@
const url = 'https://swapi.dev/api/planets'
const showData = ({data})=>{
data.results.forEach((planet) => {
console.log(planet.name)
})
return axios.get(data.next)
}
axios.get(url)
.then(showData)
.then(showData)
// axios.get(data.next).then(({ data }) => {
// data.results.forEach((planet) => { console.log(planet.name) })
// axios.get(data.next).then(({ data }) => {
// data.results.forEach((planet) => { console.log(planet.name) })
// })
// })

@ -0,0 +1,9 @@
async function getData() {
try {
const response = await axios.get('https://swapi.dev/api/planets');
console.log(response);
} catch (error) {
console.error(error);
}
}
getData();

@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="script.js"></script>
</head>
<body>
</body>
</html>

@ -0,0 +1,29 @@
const url = "https://swapi.dev/api/planets";
const checkStatusAndParse = (response)=>{
if(!response.ok) throw new Error('Status code error')
return response.json();
}
const printPlanets = (data)=>{
console.log("FETCHED ALL PLANETS")
data.results.forEach((planet)=>{
console.log(planet.name)
})
return Promise.resolve(data.next)
}
const fetchMorePlanets = (url)=>{
return fetch(url);
}
fetch(url)
.then(checkStatusAndParse)
.then(printPlanets)
.then(fetchMorePlanets)
.then(checkStatusAndParse)
.then(printPlanets)
.then(fetchMorePlanets)
.then(checkStatusAndParse)
.then(printPlanets)
.catch((err)=>{console.log(err)})

@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
<script src="script.js"></script>
</html>

@ -0,0 +1,21 @@
// function reqListener () {
// console.log(this.responseText);
// }
// var oReq = new XMLHttpRequest();
// oReq.addEventListener("load", reqListener);
// oReq.open("GET", "http://www.example.org/example.txt");
// oReq.send();
const url = "https://swapi.dev/api/planets"
const myReq = new XMLHttpRequest();
myReq.addEventListener('load', ()=>{
console.log("it works")
});
myReq.addEventListener('error', ()=>{
console.log("Error")
});
myReq.open('GET',url,true);
myReq.send();
console.log("Request sent")
console.log(myReq.response)

@ -0,0 +1,10 @@
function evenOdd(num) {
if (num % 2 === 0) {
console.log("Even")
}
else{
console.log("odd")
}
}
evenOdd(2);
evenOdd(5);

@ -0,0 +1,9 @@
function findMax(n1,n2){
if(n1<n2){
console.log(`${n2} is maximum `);
}
else{
console.log(`${n1} is maximum`);
}
}
findMax(345,3456);

@ -0,0 +1,20 @@
function findMax(n1,n2,n3){
if(n1>n2){
if(n3>n1){
console.log(`${n3} is max`);
}
else{
console.log(`${n1} is max`);
}
}
else{
if(n3>n2){
console.log(`${n3} is max`);
}
else{
console.log(`${n2} is max`)
}
}
}
findMax(23,45,24);

@ -0,0 +1,10 @@
function isVowel(al){
if(al==="a" || al=== "e" || al==="i" || al==="o" || al==="u" || al==="A" || al=== "E" || al==="I" || al==="O" || al==="U"){
console.log("vowel");
}
else{
console.log("constant");
}
}
isVowel("a");
isVowel("R");

@ -0,0 +1,8 @@
<li><a href=""></a>
<li><a href=""></a>
<li><a href=""></a>
<li><a href=""></a>
<li><a href=""></a>
<li><a href=""></a>
<li><a href=""></a>
<li><a href=""></a>

@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- <script src="storage.js"></script> -->
<script src="oop1.js"></script>
</body>
</html>

@ -0,0 +1,17 @@
localStorage.setItem('name','Tushar')
localStorage.setItem('name2', "Rahul")
let nam = localStorage.getItem('name')
console.log(nam)
// clear all the local storage
// localStorage.clear()
localStorage.removeItem('name')
const arr = ["bhindi","pyaj","Nimbu"];
localStorage.setItem('Sabzi', JSON.stringify(arr))
// ##### Session Storage ####
sessionStorage.setItem('students',JSON.stringify(['Tushar',"Rahul"]))

@ -0,0 +1,32 @@
const gameBoard = [
[4,32,8,4],
[64,8,32,2],
[8,32,16,4],
[2,8,4,2]
];
for(let i=0;i < gameBoard.length;i++){
// console.log(gameBoard[i]);
for(let j=0;j<gameBoard[i].length;j++)
{
console.log(gameBoard[i][j]);
}
}
// output---
/*
4
32
8
4
64
8
32
2
8
32
16
4
2
8
4
2
*/

@ -0,0 +1,10 @@
const randNum = (a)=>{
return Math.floor(Math.random()*a)+1;
}
let target = randNum(10);
let guess = randNum(10);
while(guess!==target){
console.log(`guess is ${guess} Trying again.....`)
guess = randNum(10);
}
console.log(`Congrats guess ${guess} was right`);

@ -0,0 +1,19 @@
const annoyer = {
phrases: [
"The best of both worlds", 'Speak of the devil','See eye to eye','Once in a blue moon',
'when pigs fly'
],
pickPhrase(){
const {phrases} = this;
const idx = Math.floor(Math.random() * phrases.length);
return phrases[idx]
},
start(){
const pickedPhrase = this.pickPhrase();
setInterval(()=>{
console.log(pickedPhrase);
console.log(this.pickPhrase())// only work with arrow function
},3000)
}
}

@ -0,0 +1,34 @@
function makeDeck() {
const deck = []
const suits = ['hearts', 'diamonds', 'spades', 'clubs'];
const values = '1,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){
return deck.pop()
}
const myDeck = makeDeck();
const card1 = drawCard(myDeck);
// makeDeck(){
// [
// {value: '5',suit:'hearts'}
// ]
// }

@ -0,0 +1,32 @@
function sayHi(){
console.log("Hii")
// this refers to the window (global scope object in the browser)
console.log(this)
}
const person = {
first: "Tushar",
last : "Rajpoot",
nickName: false,
fullName(){
// console.log(this)
return `${this.first} ${this.last}`
},
printBio(){
const fullName = this.fullName();
console.log(`${fullName} is a person`)
},
laugh: ()=>{
console.log(this);
console.log(this.nickName)
}// arrow functions don't behave that way
// this refers to window object not current object
}
console.log(person.fullName())
// now this refers to person object
person.printBio();

@ -0,0 +1,12 @@
<!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>OOPS</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>

@ -0,0 +1,91 @@
// console.log("Hello")
// String.prototype.getup = function(){
// return this.toUpperCase()
// }
// Array.prototype.pop = function(){
// return "Sorry"
// }
// console.log("Tushar".getup())
// console.log([2,3,4].pop())
// const navColor = new Color('pink',[345,354,645])
// const logoColor = new Color('green',[255,255,255])
// function hex(r,g,b){
// return '#' + ((1 << 24) + (r << 16 ) + (g << 8) + b).toString(16).slice(1)
// }
// function rgb(r,g,b){
// return `rgb(${r}, ${b}, ${g})`;
// }
// function makeColor(r, g, b) {
// const color = {}
// color.r = r;
// color.g = g;
// color.b = b;
// color.rgb = function () {
// const { r, g, b } = this;
// return `rgb(${r}, ${b}, ${g})`
// }
// color.hex = function () {
// const { r, g, b } = this;
// return '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)
// }
// return color;
// }
// const c = makeColor(23, 23, 334)
// function Car(make,model,year){
// this.make = make
// this.model = model
// this.year = year
// }
// Car.prototype.carPrice = function(){
// const {make,year,model} = this;
// return `Price(${make},${year},${model})`
// }
// let car1 = new Car("Audi", "Q7", "2022")
// class Color{
// constructor(r,g,b){
// this.r = r
// this.g = g
// this.b = b
// }
// greet(){
// const {r,g,b} = this
// return `rgb(${r}, ${g}, ${b})`
// }
// }
// const c1 = new Color(333,43,34)
class Pet {
constructor(name,age){
this.name = name
this.age = age
}
eat(){
return `${this.name} is eating`
}
}
class Cat extends Pet{
meow(){
return "MEOWWW"
}
}
class Dog extends Pet{
bark(){
return "BARKWW"
}
}
const cat1 = new Cat("Losi",5)
const dog1 = new Dog("Rockie",7)
Loading…
Cancel
Save