Merge 523f7bfa3d
into 8b41cd49c3
commit
e1c0fe6529
Binary file not shown.
Binary file not shown.
Binary file not shown.
@ -0,0 +1,2 @@
|
||||
.vscode
|
||||
.DS_Store
|
@ -0,0 +1,101 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Day 1 : JS refresher</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<h1>Hello</h1>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
<script src="1.countries.js"></script>
|
||||
<script src="1.web_techs.js"></script>
|
||||
<script src="1.array.js"></script>
|
||||
<!-- <script>
|
||||
//Exercise 1
|
||||
let myArr = ['Nam', 17, true, { country: 'Vietnam', city: 'Ho chi minh' }, { skills: ['html,css,js'] }];
|
||||
console.log('my Array: ' + myArr);
|
||||
console.log('my Array length: ' + myArr.length);
|
||||
console.log("First item: " + myArr[0]);
|
||||
console.log("Middle item: " + myArr[Math.floor(myArr.length / 2)]);
|
||||
console.log("Last item: " + myArr[myArr.length - 1]);
|
||||
|
||||
const itCompany = ['Facebook', 'Google', 'Microsoft', 'Apple', 'IBM', 'Oracle', 'Amazon'];
|
||||
console.log(itCompany);
|
||||
console.log(itCompany.length);
|
||||
console.log(itCompany[0], itCompany[Math.floor(itCompany.length / 2)], itCompany[itCompany.length - 1]);
|
||||
itCompany.forEach(com => {
|
||||
console.log(com.toUpperCase());
|
||||
});
|
||||
|
||||
itCompany.includes('Nam') ? 1 : 0;
|
||||
// Filter out companies which have more than one 'o' without the filter method
|
||||
itCompany.forEach(com => {
|
||||
const temp = com.split('');
|
||||
let count = 0;
|
||||
for (let i = 0; i < temp.length; i++) {
|
||||
if (temp[i] == 'o') count++;
|
||||
}
|
||||
if (count > 1) console.log(com);
|
||||
});
|
||||
/**
|
||||
* Sort the array using sort() method
|
||||
Reverse the array using reverse() method
|
||||
*/
|
||||
console.log(itCompany.sort());
|
||||
console.log(itCompany.reverse());
|
||||
|
||||
/**
|
||||
* Slice out the first 3 companies from the array
|
||||
Slice out the last 3 companies from the array
|
||||
Slice out the middle IT company or companies from the array
|
||||
*/
|
||||
console.log(itCompany.slice(0, 2));
|
||||
console.log(itCompany.slice(itCompany.length - 3, itCompany.length - 1));
|
||||
console.log(itCompany.slice(Math.floor(itCompany.length / 2), Math.floor(itCompany.length / 2) + 1));
|
||||
/*
|
||||
Remove the first IT company from the array
|
||||
Remove the middle IT company or companies from the array
|
||||
Remove the last IT company from the array
|
||||
Remove all IT companies
|
||||
*/
|
||||
console.log(itCompany.shift());
|
||||
console.log(itCompany.splice(Math.floor(itCompany.length / 2), 1));
|
||||
console.log(itCompany.pop());
|
||||
console.log(itCompany.splice());
|
||||
|
||||
|
||||
//exercise 2
|
||||
let text = 'I love teaching and empowering people. I teach HTML, CSS, JS, React, Python.';
|
||||
let words = text.split('.').join('').split(' ');
|
||||
console.log(words);
|
||||
console.log(words.length);
|
||||
|
||||
const shoppingCart = ['Milk', 'Coffee', 'Tea', 'Honey'];
|
||||
/**
|
||||
* add 'Meat' in the beginning of your shopping cart if it has not been already added
|
||||
add Sugar at the end of you shopping cart if it has not been already added
|
||||
remove 'Honey' if you are allergic to honey
|
||||
modify Tea to 'Green Tea'
|
||||
*/
|
||||
|
||||
if (!shoppingCart.includes('Meat')) shoppingCart.unshift('Meat');
|
||||
if (!shoppingCart.includes('Sugar')) shoppingCart.push('Sugar');
|
||||
const indexOfHoney = shoppingCart.indexOf('Honey');
|
||||
shoppingCart.splice(indexOfHoney, 1);
|
||||
const indexOfTea = shoppingCart.indexOf('Tea');
|
||||
shoppingCart[indexOfTea] = 'Green Tea';
|
||||
|
||||
|
||||
//In countries array check if 'Ethiopia' exists in the array if it exists print 'ETHIOPIA'. If it does not exist add to the countries list.
|
||||
|
||||
countries.includes('Ethiopia') ? console.log('Ethiopia') : countries.push('Ethiopia');
|
||||
|
||||
//In the webTechs array check if Sass exists in the array and if it exists print 'Sass is a CSS preprocess'. If it does not exist add Sass to the array and print the array.
|
||||
|
||||
webtechs.includes('Sass') ? console.log('Sass is a CSS preprocess') : webtechs.push('Sass'); console.log(webtechs);
|
||||
</script> -->
|
@ -0,0 +1,120 @@
|
||||
//Exercise 1
|
||||
let myArr = ['Nam', 17, true, { country: 'Vietnam', city: 'Ho chi minh' }, { skills: ['html,css,js'] }];
|
||||
console.log('my Array: '+myArr);
|
||||
console.log('my Array length: ' + myArr.length);
|
||||
console.log("First item: " + myArr[0]);
|
||||
console.log("Middle item: " + myArr[Math.floor(myArr.length / 2)]);
|
||||
console.log("Last item: " + myArr[myArr.length - 1]);
|
||||
|
||||
const itCompany = ['Facebook', 'Google', 'Microsoft', 'Apple', 'IBM', 'Oracle', 'Amazon'];
|
||||
console.log(itCompany);
|
||||
console.log(itCompany.length);
|
||||
console.log(itCompany[0], itCompany[Math.floor(itCompany.length / 2)], itCompany[itCompany.length - 1]);
|
||||
itCompany.forEach(com => {
|
||||
console.log(com.toUpperCase());
|
||||
});
|
||||
|
||||
itCompany.includes('Nam') ? 1 : 0;
|
||||
// Filter out companies which have more than one 'o' without the filter method
|
||||
itCompany.forEach(com => {
|
||||
const temp = com.split('');
|
||||
let count = 0;
|
||||
for (let i = 0; i < temp.length; i++) {
|
||||
if (temp[i] == 'o') count++;
|
||||
}
|
||||
if (count > 1) console.log(com);
|
||||
});
|
||||
/**
|
||||
* Sort the array using sort() method
|
||||
Reverse the array using reverse() method
|
||||
*/
|
||||
console.log(itCompany.sort());
|
||||
console.log(itCompany.reverse());
|
||||
|
||||
/**
|
||||
* Slice out the first 3 companies from the array
|
||||
Slice out the last 3 companies from the array
|
||||
Slice out the middle IT company or companies from the array
|
||||
*/
|
||||
console.log(itCompany.slice(0, 2));
|
||||
console.log(itCompany.slice(itCompany.length - 3, itCompany.length - 1));
|
||||
console.log(itCompany.slice(Math.floor(itCompany.length / 2), Math.floor(itCompany.length / 2) + 1));
|
||||
/*
|
||||
Remove the first IT company from the array
|
||||
Remove the middle IT company or companies from the array
|
||||
Remove the last IT company from the array
|
||||
Remove all IT companies
|
||||
*/
|
||||
console.log(itCompany.shift());
|
||||
console.log(itCompany.splice(Math.floor(itCompany.length / 2), 1));
|
||||
console.log(itCompany.pop());
|
||||
console.log(itCompany.splice());
|
||||
|
||||
|
||||
//exercise 2
|
||||
let text ='I love teaching and empowering people. I teach HTML, CSS, JS, React, Python.';
|
||||
let words = text.split('.').join('').split(' ');
|
||||
console.log(words);
|
||||
console.log(words.length);
|
||||
|
||||
const shoppingCart = ['Milk', 'Coffee', 'Tea', 'Honey'];
|
||||
/**
|
||||
* add 'Meat' in the beginning of your shopping cart if it has not been already added
|
||||
add Sugar at the end of you shopping cart if it has not been already added
|
||||
remove 'Honey' if you are allergic to honey
|
||||
modify Tea to 'Green Tea'
|
||||
*/
|
||||
|
||||
if (!shoppingCart.includes('Meat')) shoppingCart.unshift('Meat');
|
||||
if (!shoppingCart.includes('Sugar')) shoppingCart.push('Sugar');
|
||||
const indexOfHoney = shoppingCart.indexOf('Honey');
|
||||
shoppingCart.splice(indexOfHoney, 1);
|
||||
const indexOfTea = shoppingCart.indexOf('Tea');
|
||||
shoppingCart[indexOfTea] = 'Green Tea';
|
||||
|
||||
|
||||
//In countries array check if 'Ethiopia' exists in the array if it exists print 'ETHIOPIA'. If it does not exist add to the countries list.
|
||||
countries.includes('Ethiopia') ? console.log('Ethiopia') : countries.push('Ethiopia');
|
||||
|
||||
//In the webTechs array check if Sass exists in the array and if it exists print 'Sass is a CSS preprocess'. If it does not exist add Sass to the array and print the array.
|
||||
webtechs.includes('Sass') ? console.log('Sass is a CSS preprocess') : webtechs.push('Sass'); console.log(webtechs);
|
||||
// Concatenate the following two variables and store it in a fullStack variable.
|
||||
const frontEnd = ['HTML', 'CSS', 'JS', 'React', 'Redux'];
|
||||
const backEnd = ['Node', 'Express', 'MongoDB'];
|
||||
const fullStack = frontEnd.concat(backEnd);
|
||||
console.log('Fullstack: ' + fullStack);
|
||||
//Excersie 3
|
||||
// The following is an array of 10 students ages: js const ages = [19, 22, 19, 24, 20, 25, 26, 24, 25, 24] - Sort the array and find the min and max age - Find the median age(one middle item or two middle items divided by two) - Find the average age(all items divided by number of items) - Find the range of the ages(max minus min) - Compare the value of (min - average) and (max - average), use abs() method
|
||||
const ages = [19, 22, 19, 24, 20, 25, 26, 24, 25, 24];
|
||||
console.log(ages.sort());
|
||||
agesMedianIdx = (ages.length - 1) / 2;
|
||||
console.log("median age: " + ages[Math.floor(agesMedianIdx)]);
|
||||
let totalAge = 0;
|
||||
ages.forEach(age => {
|
||||
totalAge += age;
|
||||
});
|
||||
const avgAge = totalAge / ages.length;
|
||||
console.log("Average age: " + avgAge);
|
||||
const minAge = Math.min(...ages);
|
||||
console.log("Min age: " + minAge);
|
||||
const maxAge = Math.max(...ages);
|
||||
console.log("Max age: " + maxAge);
|
||||
console.log("Range of the ages: " + (maxAge - minAge));
|
||||
console.log("Compare min vs avg: " + Math.abs(minAge - avgAge));
|
||||
console.log("Compare max vs avg: " + Math.abs(maxAge - avgAge));
|
||||
// 1.Slice the first ten countries from the countries array
|
||||
console.log("first ten countries: " + countries.slice(0, 10));
|
||||
// Find the middle country(ies) in the countries array
|
||||
const countryMid = countries.length/2;
|
||||
console.log("middle country: " + countries.slice(countryMid, countryMid + 1));
|
||||
// Divide the countries array into two equal arrays if it is even. If countries array is not even , one more country for the first half.
|
||||
let firstHalfCountries = [];
|
||||
let secondHalfCountries = [];
|
||||
for (let i = 0; i < countries.length; i++) {
|
||||
const con = countries[i];
|
||||
if (i <= countryMid) { firstHalfCountries.push(con);}
|
||||
else { secondHalfCountries.push(con); }
|
||||
|
||||
}
|
||||
console.log("first half: " + firstHalfCountries);
|
||||
console.log("second half: " + secondHalfCountries);
|
@ -0,0 +1,13 @@
|
||||
let countries = [
|
||||
'Albania',
|
||||
'Bolivia',
|
||||
'Canada',
|
||||
'Denmark',
|
||||
'Ethiopia',
|
||||
'Finland',
|
||||
'Germany',
|
||||
'Hungary',
|
||||
'Ireland',
|
||||
'Japan',
|
||||
'Kenya',
|
||||
]
|
@ -0,0 +1,9 @@
|
||||
var webtechs = [
|
||||
'HTML',
|
||||
'CSS',
|
||||
'JavaScript',
|
||||
'React',
|
||||
'Redux',
|
||||
'Node',
|
||||
'MongoDB',
|
||||
];
|
@ -0,0 +1,42 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>If-else conditional statement</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
||||
<script>
|
||||
//Exercise lv1
|
||||
// var age = window.prompt("Enter your age!");
|
||||
// if (age >= 18) {
|
||||
// alert("You are old enough to drive");
|
||||
// } else {
|
||||
// let ageNeed = 18 - age;
|
||||
// alert(`You are left with ${ageNeed} to drive!`);
|
||||
// }
|
||||
|
||||
|
||||
// var yourAge = window.prompt("Enter your age!");
|
||||
// (yourAge > 20) ? alert("You are older than me.") : alert("You are younger than me!");
|
||||
//Exercise 2
|
||||
let grade = window.prompt("Enter grade: ");
|
||||
if (grade >= 0 && grade <= 100) {
|
||||
if (grade >= 80 && grade <= 100) {
|
||||
alert("A");
|
||||
} else if (grade >= 70) {
|
||||
alert("B");
|
||||
} else if (grade >= 60) {
|
||||
alert("C");
|
||||
} else if (grade >= 50) {
|
||||
alert("D");
|
||||
} else alert("F")
|
||||
}
|
||||
|
||||
</script>
|
@ -0,0 +1,211 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Object</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
||||
<script>
|
||||
// const users = {
|
||||
// Alex: {
|
||||
// email: 'alex@alex.com',
|
||||
// skills: ['HTML', 'CSS', 'JavaScript'],
|
||||
// age: 20,
|
||||
// isLoggedIn: false,
|
||||
// points: 30
|
||||
// },
|
||||
// Asab: {
|
||||
// email: 'asab@asab.com',
|
||||
// skills: ['HTML', 'CSS', 'JavaScript', 'Redux', 'MongoDB', 'Express', 'React', 'Node'],
|
||||
// age: 25,
|
||||
// isLoggedIn: false,
|
||||
// points: 50
|
||||
// },
|
||||
// Brook: {
|
||||
// email: 'daniel@daniel.com',
|
||||
// skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux'],
|
||||
// age: 30,
|
||||
// isLoggedIn: true,
|
||||
// points: 50
|
||||
// },
|
||||
// Daniel: {
|
||||
// email: 'daniel@alex.com',
|
||||
// skills: ['HTML', 'CSS', 'JavaScript', 'Python'],
|
||||
// age: 20,
|
||||
// isLoggedIn: false,
|
||||
// points: 40
|
||||
// },
|
||||
// John: {
|
||||
// email: 'john@john.com',
|
||||
// skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux', 'Node.js'],
|
||||
// age: 20,
|
||||
// isLoggedIn: true,
|
||||
// points: 50
|
||||
// },
|
||||
// Thomas: {
|
||||
// email: 'thomas@thomas.com',
|
||||
// skills: ['HTML', 'CSS', 'JavaScript', 'React'],
|
||||
// age: 20,
|
||||
// isLoggedIn: false,
|
||||
// points: 40
|
||||
// },
|
||||
// Paul: {
|
||||
// email: 'paul@paul.com',
|
||||
// skills: ['HTML', 'CSS', 'JavaScript', 'MongoDB', 'Express', 'React', 'Node'],
|
||||
// age: 20,
|
||||
// isLoggedIn: false,
|
||||
// points: 40
|
||||
// }
|
||||
// };
|
||||
// //TODO: Find the person who has many skills in the users object.
|
||||
// const copyUsers = Object.assign({},users);
|
||||
// const usersKeys = Object.keys(copyUsers);
|
||||
// const usersValues = Object.values(copyUsers);
|
||||
// const usersEntries = Object.entries(copyUsers);
|
||||
// // usersValues.forEach(value => {
|
||||
// // console.log(value.skills)
|
||||
// // });
|
||||
|
||||
|
||||
// usersKeys.forEach(person => {
|
||||
// // count logged in users, count users having greater than equal to 50 points from the following object.
|
||||
// // if(copyUsers[person].points >= 50){
|
||||
// // console.log(person);
|
||||
// // }
|
||||
|
||||
// //Find people who are MERN stack developer from the users object
|
||||
// const skills = copyUsers[person].skills;
|
||||
// if(skills.includes('MongoDB') && skills.includes('Express') && skills.includes('React') && skills.includes('Node')){
|
||||
// console.log("MERN stacker: "+ person);
|
||||
// }
|
||||
// });
|
||||
// users.Nam = {
|
||||
// email: 'nam@nam.com',
|
||||
// skills: ['HTML', 'CSS', 'JavaScript', 'MongoDB', 'Express', 'React', 'Node'],
|
||||
// age: 20,
|
||||
// isLoggedIn: false,
|
||||
// points: 100
|
||||
// };
|
||||
// Set your name in the users object without modifying the original users object
|
||||
// console.log(users);
|
||||
|
||||
//Exercise lv3
|
||||
const users = [
|
||||
{
|
||||
_id: 'ab12ex',
|
||||
username: 'Alex',
|
||||
email: 'alex@alex.com',
|
||||
password: '123123',
|
||||
createdAt: '08/01/2020 9:00 AM',
|
||||
isLoggedIn: false,
|
||||
},
|
||||
{
|
||||
_id: 'fg12cy',
|
||||
username: 'Asab',
|
||||
email: 'asab@asab.com',
|
||||
password: '123456',
|
||||
createdAt: '08/01/2020 9:30 AM',
|
||||
isLoggedIn: true,
|
||||
},
|
||||
{
|
||||
_id: 'zwf8md',
|
||||
username: 'Brook',
|
||||
email: 'brook@brook.com',
|
||||
password: '123111',
|
||||
createdAt: '08/01/2020 9:45 AM',
|
||||
isLoggedIn: true,
|
||||
},
|
||||
{
|
||||
_id: 'eefamr',
|
||||
username: 'Martha',
|
||||
email: 'martha@martha.com',
|
||||
password: '123222',
|
||||
createdAt: '08/01/2020 9:50 AM',
|
||||
isLoggedIn: false,
|
||||
},
|
||||
{
|
||||
_id: 'ghderc',
|
||||
username: 'Thomas',
|
||||
email: 'thomas@thomas.com',
|
||||
password: '123333',
|
||||
createdAt: '08/01/2020 10:00 AM',
|
||||
isLoggedIn: false,
|
||||
}
|
||||
]
|
||||
// .a.Create a function called signUp which allows user to add to the collection.If user exists, inform the user that he has already an account.
|
||||
function signUp(user) {
|
||||
for (let i = 0; i < users.length; i++) {
|
||||
const usr = users[i];
|
||||
if (usr[username] === user[username]) {
|
||||
console.log('The user is already existed');
|
||||
break;
|
||||
}
|
||||
users.push(user);
|
||||
};
|
||||
}
|
||||
|
||||
function signIn(user) {
|
||||
user.isLoggedIn = true;
|
||||
}
|
||||
|
||||
|
||||
signIn(users[4]);
|
||||
console.log(users[4]);
|
||||
|
||||
const products = [
|
||||
{
|
||||
_id: 'eedfcf',
|
||||
name: 'mobile phone',
|
||||
description: 'Huawei Honor',
|
||||
price: 200,
|
||||
ratings: [
|
||||
{ userId: 'fg12cy', rate: 5 },
|
||||
{ userId: 'zwf8md', rate: 4.5 },
|
||||
],
|
||||
likes: [],
|
||||
},
|
||||
{
|
||||
_id: 'aegfal',
|
||||
name: 'Laptop',
|
||||
description: 'MacPro: System Darwin',
|
||||
price: 2500,
|
||||
ratings: [],
|
||||
likes: ['fg12cy'],
|
||||
},
|
||||
{
|
||||
_id: 'hedfcg',
|
||||
name: 'TV',
|
||||
description: 'Smart TV:Procaster',
|
||||
price: 400,
|
||||
ratings: [{ userId: 'fg12cy', rate: 5 }],
|
||||
likes: ['fg12cy'],
|
||||
},
|
||||
]
|
||||
// a. Create a function called rateProduct which rates the product
|
||||
function rateProduct(userId, rate, proId) {
|
||||
for (let i = 0; i < products.length; i++) {
|
||||
const pro = products[i];
|
||||
if (pro[_id] === proId) {
|
||||
pro[ratings].push({ userId, rate });
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
//b. Create a function called averageRating which calculate the average rating of a product
|
||||
function likeProduct(userId, proId) {
|
||||
for (let i = 0; i < products.length; i++) {
|
||||
const pro = products[i];
|
||||
if (pro[_id] === proId) {
|
||||
pro[likes].push(userId);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
@ -0,0 +1,81 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Function</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
||||
<script>
|
||||
function makeid(length) {
|
||||
var result = '';
|
||||
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
|
||||
var charactersLength = characters.length;
|
||||
for (var i = 0; i < length; i++) {
|
||||
result += characters.charAt(Math.floor(Math.random() * charactersLength));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
function userIdGeneratedByUser() {
|
||||
let numOfCha = window.prompt("Number of characters?: ");
|
||||
let numOfId = window.prompt("Number of id to be generate?: ");
|
||||
let arrOfId = [];
|
||||
for (let i = 0; i < numOfId; i++) {
|
||||
arrOfId[i] = makeid(numOfCha);
|
||||
}
|
||||
return arrOfId;
|
||||
}
|
||||
|
||||
function generateColors(type, quantity) {
|
||||
let arrOfColor = [];
|
||||
if (type === 'hexa') {
|
||||
for (let i = 0; i < quantity; i++) {
|
||||
var randomColor = Math.floor(Math.random() * 16777215).toString(16);
|
||||
arrOfColor[i] = '#' + randomColor;
|
||||
}
|
||||
} else if (type === 'rgb') {
|
||||
for (let i = 0; i < quantity; i++) {
|
||||
const randomBetween = (min, max) => min + Math.floor(Math.random() * (max - min + 1));
|
||||
const r = randomBetween(0, 255);
|
||||
const g = randomBetween(0, 255);
|
||||
const b = randomBetween(0, 255);
|
||||
arrOfColor[i] = `rgb(${r},${g},${b})`;
|
||||
}
|
||||
}
|
||||
return arrOfColor;
|
||||
}
|
||||
|
||||
function average(arr) {
|
||||
let avg = 0;
|
||||
let sum = 0;
|
||||
for (let i = 0; i < arr.length; i++) {
|
||||
const element = arr[i];
|
||||
if (typeof (element) === "number") {
|
||||
sum += element;
|
||||
} else {
|
||||
return 'The array contains non-number element!';
|
||||
}
|
||||
}
|
||||
return avg = sum / arr.length;
|
||||
}
|
||||
|
||||
function shuffleArray(arr) {
|
||||
let i = arr.length;
|
||||
let j = 0;
|
||||
while (i--) {
|
||||
j = Math.floor(Math.random() * (i + 1));
|
||||
temp = arr[i];
|
||||
arr[i] = arr[j];
|
||||
arr[j] = temp;
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
</script>
|
@ -0,0 +1,45 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Destructuring</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
||||
<script>
|
||||
const person = {
|
||||
firstName: 'Asabeneh',
|
||||
lastName: 'Yetayeh',
|
||||
age: 250,
|
||||
country: 'Finland',
|
||||
job: 'Instructor and Developer',
|
||||
skills: [
|
||||
'HTML',
|
||||
'CSS',
|
||||
'JavaScript',
|
||||
'React',
|
||||
'Redux',
|
||||
'Node',
|
||||
'MongoDB',
|
||||
'Python',
|
||||
'D3.js',
|
||||
],
|
||||
languages: ['Amharic', 'English', 'Suomi(Finnish)'],
|
||||
}
|
||||
const getPersonInfo = ({ firstName, lastName, age, country, job, skills, languages }) => {
|
||||
const lastSkill = skills.splice(skills.length - 1, 1);
|
||||
const lastLang = languages.splice(languages.length - 1, 1);
|
||||
return `${firstName} lives in ${country}. He is ${age} years old. He is an ${job}. He teaches ${skills} and ${lastSkill}. He speaks ${languages} and a little bit of ${lastLang}.`
|
||||
};
|
||||
|
||||
console.log(getPersonInfo(person));
|
||||
/*
|
||||
Asabeneh Yetayeh lives in Finland. He is 250 years old. He is an Instructor and Developer. He teaches HTML, CSS, JavaScript, React, Redux, Node, MongoDB, Python and D3.js. He speaks Amharic, English and a little bit of Suomi(Finnish)
|
||||
*/
|
||||
</script>
|
@ -0,0 +1,86 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Programming function</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
||||
<script>
|
||||
const products = [
|
||||
{ product: 'banana', price: 3 },
|
||||
{ product: 'mango', price: 6 },
|
||||
{ product: 'potato', price: ' ' },
|
||||
{ product: 'avocado', price: 8 },
|
||||
{ product: 'coffee', price: 10 },
|
||||
{ product: 'tea', price: '' },
|
||||
]
|
||||
|
||||
products.forEach(({ product: pro, price }) => {
|
||||
console.log(`The price of ${pro} is ${price} euros.`)
|
||||
});
|
||||
|
||||
let sum = 0;
|
||||
products.forEach(({ product: pro, price }) => {
|
||||
if (typeof (price) === "number") {
|
||||
sum += price;
|
||||
}
|
||||
});
|
||||
console.log('Sum by forEach: ' + sum);
|
||||
|
||||
let prices = products.map(({ product: pro, price }) => price);
|
||||
console.log(prices);
|
||||
|
||||
let proWithPrice = products.filter(({ product: pro, price }) => {
|
||||
if (typeof (price) === "number") {
|
||||
return pro;
|
||||
}
|
||||
});
|
||||
console.log(proWithPrice);
|
||||
|
||||
|
||||
let sumOfPrices = products.map(({ product: pro, price }) => price).filter(price =>
|
||||
typeof (price) === "number" ? price : 0
|
||||
).reduce((acc, cur) => acc + cur);
|
||||
|
||||
console.log('Sum by chainning: ' + sumOfPrices);
|
||||
|
||||
|
||||
let sumOfPrices2 = products.reduce((acc, { product: pro, price }) => {
|
||||
return acc += (typeof (price) === "number") ? price : 0;
|
||||
}, 0);
|
||||
|
||||
console.log('Sum by only reduce: ' + sumOfPrices2);
|
||||
|
||||
let proWithoutPrice = products.find(({ product: pro, price }) => {
|
||||
if (!(typeof (price) === "number")) {
|
||||
return pro;
|
||||
}
|
||||
});
|
||||
console.log(proWithoutPrice);
|
||||
|
||||
let proWithoutPrice2 = products.findIndex(({ product: pro, price }) => {
|
||||
if (!(typeof (price) === "number")) {
|
||||
return pro;
|
||||
}
|
||||
});
|
||||
console.log(proWithoutPrice2);
|
||||
|
||||
let proWithoutPrice3 = products.some(({ product: pro, price }) => !(typeof (price) === "number"));
|
||||
console.log(proWithoutPrice3);
|
||||
|
||||
let proWithPrice2 = products.every(({ product: pro, price }) => typeof (price) === "number");
|
||||
console.log(proWithPrice2);
|
||||
|
||||
//forEach doesn't require to be returned
|
||||
//map, filter return an array
|
||||
//reduce return a value of sum/multiply
|
||||
//filter returns all the item matches condition, find only returns 1st item matches, findIndex returns the index whose item matches
|
||||
//some returns true if any item matches the condition, every returns true if all items matches the condition
|
||||
</script>
|
@ -0,0 +1,151 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Class
|
||||
|
||||
</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
||||
<script>
|
||||
ages = [31, 26, 34, 37, 27, 26, 32, 32, 26, 27, 27, 24, 32, 33, 27, 25, 26, 38, 37, 31, 34, 24, 33, 29, 26];
|
||||
|
||||
class Statistic {
|
||||
|
||||
constructor(sample) {
|
||||
this.sample = sample;
|
||||
this.count = 0;
|
||||
this.sum = 0;
|
||||
this.min = 0;
|
||||
this.max = 0;
|
||||
this.range = 0;
|
||||
this.mean = 0;
|
||||
this.median = 0;
|
||||
this.mode = {};
|
||||
this.variance = 0;
|
||||
this.standardDeviation = 0;
|
||||
this.frequenDist = [];
|
||||
}
|
||||
|
||||
getcount() {
|
||||
return this.count = this.sample.length;
|
||||
}
|
||||
|
||||
getsum() {
|
||||
return this.sum = this.sample.reduce((acc, cur) => acc + cur);
|
||||
}
|
||||
|
||||
getmin() {
|
||||
return this.min = Math.min(...this.sample);
|
||||
}
|
||||
|
||||
getmax() {
|
||||
return this.max = Math.max(...this.sample);
|
||||
}
|
||||
getrange() {
|
||||
return this.max - this.min;
|
||||
}
|
||||
getmean() {
|
||||
return this.mean = this.sum / this.count;
|
||||
}
|
||||
|
||||
getmedian() {
|
||||
const arrSort = this.sample.sort();
|
||||
const mid = Math.ceil(arrSort.length / 2);
|
||||
return this.median = arrSort.length % 2 == 0 ? (arrSort[mid] + arrSort[mid - 1]) / 2 : arrSort[mid - 1];
|
||||
}
|
||||
|
||||
getmode() {
|
||||
const a = this.sample.sort();
|
||||
const count = {};
|
||||
|
||||
a.forEach(e => {
|
||||
if (!(e in count)) {
|
||||
count[e] = 0;
|
||||
}
|
||||
count[e]++;
|
||||
});
|
||||
|
||||
let bestElement;
|
||||
let bestCount = 0;
|
||||
|
||||
Object.entries(count).forEach(([k, v]) => {
|
||||
if (v > bestCount) {
|
||||
bestElement = k;
|
||||
bestCount = v;
|
||||
}
|
||||
});
|
||||
|
||||
return this.mode = { bestElement, bestCount };
|
||||
}
|
||||
|
||||
getvar() {
|
||||
const a = this.sample.sort();
|
||||
const SS = a.reduce((acc, cur) => acc + Math.pow((cur - this.mean), 2));
|
||||
return this.variance = SS / (this.count - 1);
|
||||
}
|
||||
|
||||
getstd() {
|
||||
return this.standardDeviation = Math.sqrt(this.variance);
|
||||
}
|
||||
|
||||
getfreqDist() {
|
||||
|
||||
const a = this.sample.sort();
|
||||
const count = {};
|
||||
a.forEach(e => {
|
||||
if (!(e in count)) {
|
||||
count[e] = 0;
|
||||
}
|
||||
count[e]++;
|
||||
});
|
||||
let i = 0;
|
||||
let fre = [];
|
||||
Object.entries(count).forEach(([k, v]) => {
|
||||
fre[i] = { num: k, freq: ((v / (a.length)) * 100).toPrecision(2) };
|
||||
i++;
|
||||
});
|
||||
|
||||
return this.frequenDist = fre;
|
||||
}
|
||||
|
||||
describe() {
|
||||
console.log(`
|
||||
Count: ${this.count},
|
||||
Sum: ${this.sum},
|
||||
Min: ${this.min},
|
||||
Max: ${this.max},
|
||||
Range: ${this.range},
|
||||
Mean: ${this.mean},
|
||||
Median: ${this.median},
|
||||
Mode: ${this.mode},
|
||||
Variance: ${this.variance},
|
||||
Standard Deviation: ${this.standardDeviation},
|
||||
Frequency Distribution: ${this.frequenDist}
|
||||
`);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
let stat = new Statistic(ages);
|
||||
console.log('Count:', stat.getcount()); // 25
|
||||
console.log('Sum: ', stat.getsum()); // 744
|
||||
console.log('Min: ', stat.getmin()); // 24
|
||||
console.log('Max: ', stat.getmax());// 38
|
||||
console.log('Range: ', stat.getrange());// 14
|
||||
console.log('Mean: ', stat.getmean());// 30
|
||||
console.log('Median: ', stat.getmedian());// 29
|
||||
console.log('Mode: ', stat.getmode()); // {'mode': 26, 'count': 5}
|
||||
console.log('Variance: ', stat.getvar()); // 17.5
|
||||
console.log('Standard Deviation: ', stat.getstd()); // 4.2
|
||||
console.log('Variance: ', stat.getvar()); // 17.5
|
||||
console.log('Frequency Distribution: ', stat.getfreqDist()); // [(20.0, 26), (16.0, 27), (12.0, 32), (8.0, 37), (8.0, 34), (8.0, 33), (8.0, 31), (8.0, 24), (4.0, 38), (4.0, 29), (4.0, 25)]
|
||||
stat.describe();
|
||||
</script>
|
Loading…
Reference in new issue