├── .vscode
└── settings.json
├── Day-1
├── data-types.js
└── variable.js
├── Day-10
├── level-1.js
├── level-2.js
└── level-3.js
├── Day-11
├── level-1.js
├── level-2.js
└── level-3.js
├── Day-12
└── level-1.js
├── Day-13
├── level-1.js
├── level-2.js
└── level-3.js
├── Day-15
├── level-1.js
├── level-2.js
└── level-3.js
├── Day-16
├── level-1.js
├── level-2.js
└── level-3.js
├── Day-17
├── level-1.js
└── level-2.js
├── Day-18
└── level-1.js
├── Day-19
└── level-1.js
├── Day-2
├── arithmetic-operators.js
├── booleans-part.js
└── strings-part.js
├── Day-21
├── level-1
│ ├── index.html
│ └── script.js
├── level-2
│ ├── index.html
│ └── script.js
└── level-3
│ ├── index.html
│ └── script.js
├── Day-22
├── level-1
│ ├── index.html
│ └── script.js
└── level-2
│ ├── index.html
│ └── script.js
├── Day-23
├── level-1
│ ├── index.html
│ └── script.js
└── level-2
│ ├── index.html
│ └── script.js
├── Day-24
└── level-1
│ ├── app.js
│ ├── images
│ ├── earth.png
│ ├── galaxy.gif
│ ├── jupiter.png
│ ├── mars.png
│ ├── mercury.png
│ ├── moon.png
│ ├── neptune.png
│ ├── pluto.png
│ ├── saturn.png
│ ├── uranus.png
│ └── venus.png
│ └── index.html
├── Day-3
├── arithmetic-operators.js
└── data-types.js
├── Day-4
└── conditionals.js
├── Day-5
├── array.js
├── countries.js
├── index.html
├── main.js
└── webtech.js
├── Day-6
└── loops.js
├── Day-7
└── functions.js
├── Day-8
├── level-1.js
├── level-2.js
└── level-3.js
├── Day-9
├── level-1.js
└── level-2.js
└── README.md
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "liveServer.settings.port": 5501
3 | }
--------------------------------------------------------------------------------
/Day-1/data-types.js:
--------------------------------------------------------------------------------
1 | let text = "victor"
2 | let isStudent = true;
3 | let hobbies;
4 | let girlfriends = null;
5 |
6 | console.log(typeof text);
7 | console.log(typeof isStudent);
8 | console.log(typeof hobbies);
9 | console.log(typeof girlfriends);
10 |
11 | // let name, lName, age, sex;
12 |
13 | // let name = "victor"
14 | // let lName = "kenneth"
15 | // let age = 19
16 | // let sex = "male";
17 |
18 | let name = "victor",
19 | lName = "kenneth",
20 | age = 19,
21 | sex = "male";
22 | let yourAge = 30;
23 | console.log(`i am ${age} years old`);
24 | console.log(`you are ${yourAge} years old`);
--------------------------------------------------------------------------------
/Day-1/variable.js:
--------------------------------------------------------------------------------
1 | //comments can make code readable
2 | //welcome to 30DaysOfJavaScript
3 | /**
4 | * comments can make code
5 | * readable
6 | * easy to use
7 | * informative
8 | */
9 |
10 | let text = "victor"
11 | let isStudent = true;
12 | let hobbies;
13 | let girlfriends = null;
14 |
15 | console.log(typeof text);
16 | console.log(typeof isStudent);
17 | console.log(typeof hobbies);
18 | console.log(typeof girlfriends);
--------------------------------------------------------------------------------
/Day-10/level-1.js:
--------------------------------------------------------------------------------
1 | //Set
2 |
3 | let set = new Set();
4 | for (let i = 0; i <= 10; i++) {
5 | set.add(i);
6 | }
7 | console.log(set);
8 | set.delete(5);
9 | console.log(set)
10 | set.clear();
11 |
12 | let names = ["victor", "fred", "ryan", "femi", "badejo"]
13 | let namesSet = new Set();
14 | names.forEach(name => {
15 | set.add(name)
16 | })
17 | console.log(set)
18 |
19 | let countries = ["nigeria", "U.S.A", "germany", "england", "italy"]
20 | let countriesLength = new Set();
21 | for (let i = 0; i < countries.length; i++){
22 | countriesLength.add(countries[i])
23 | countriesLength.add(countries[i].length);
24 | }
25 | console.log(countriesLength);
--------------------------------------------------------------------------------
/Day-10/level-2.js:
--------------------------------------------------------------------------------
1 | let a = [ 4, 5, 8, 9]
2 | let b = [3, 4, 5, 7]
3 | let A = new Set(a);
4 | let B = new Set(b);
5 |
6 | let intersection = a.filter(num => {
7 | return B.has(num)
8 | })
9 | console.log(intersection)
10 |
11 | let union = [...a, ...b]
12 | console.log(union);
13 |
14 |
--------------------------------------------------------------------------------
/Day-10/level-3.js:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/3KINGZ/30-Days-of-JavaScript-Solutions/9577eace2fa1b5bbf1fecd187e79a9e3244d4ee6/Day-10/level-3.js
--------------------------------------------------------------------------------
/Day-11/level-1.js:
--------------------------------------------------------------------------------
1 | //Array destructuring
2 | const values = [2.72, 3.14, 9.81, 37, 100];
3 | let [e, pi, gravity, humanBodyTemp, waterBoilingPoint] = values;
4 | console.log(e, pi, gravity, humanBodyTemp, waterBoilingPoint);
5 |
6 | let countries = ["finland", "estonia", "sweden", "denmark", "norway"];
7 | let [fin, est, sweden, den, nor] = countries;
8 | console.log(fin, est, sweden, den, nor)
9 |
10 | //object destructuring
11 | let rectangle = {
12 | width: 7.23,
13 | height: 3.45
14 | }
15 |
16 | let {
17 | width: w,
18 | height: h
19 | } = rectangle;
20 | console.log(w, h)
21 |
22 |
23 | let countries = [{
24 | name: "nigeria",
25 | capital: "fct",
26 | population: "7billion",
27 | languages: ["hausa", "igbo", "yoruba"]
28 | },
29 | {
30 | name: "germany",
31 | capital: "munich",
32 | population: "5billion",
33 | languages: ["german"]
34 | }, {
35 | name: "italy",
36 | capital: "rome",
37 | population: "6billion",
38 | languages: ["italian", "latin"]
39 | },
40 | {
41 | name: "france",
42 | capital: "paris",
43 | population: "6billion",
44 | languages: ["french"]
45 | }
46 | ]
47 |
48 | let [name, capital, population, languages] = countries;
49 | console.log(name, capital, population, languages);
50 |
51 | const student = ['David', ['HTM', 'CSS', 'JS', 'React'],
52 | [98, 85, 90, 95]
53 | ]
54 | let [name, skills, scores, javaScriptScores, reactScores] = student;
55 | console.log(name, skills, scores, javaScriptScores, reactScores)
56 |
57 |
--------------------------------------------------------------------------------
/Day-11/level-2.js:
--------------------------------------------------------------------------------
1 | const users = [{
2 | name: 'Brook',
3 | scores: 75,
4 | skills: ['HTM', 'CSS', 'JS'],
5 | age: 16
6 | },
7 | {
8 | name: 'Alex',
9 | scores: 80,
10 | skills: ['HTM', 'CSS', 'JS'],
11 | age: 18
12 | },
13 | {
14 | name: 'David',
15 | scores: 75,
16 | skills: ['HTM', 'CSS'],
17 | age: 22
18 | },
19 | {
20 | name: 'John',
21 | scores: 85,
22 | skills: ['HTML'],
23 | age: 25
24 | },
25 | {
26 | name: 'Sara',
27 | scores: 95,
28 | skills: ['HTM', 'CSS', 'JS'],
29 | age: 26
30 | },
31 | {
32 | name: 'Martha',
33 | scores: 80,
34 | skills: ['HTM', 'CSS', 'JS'],
35 | age: 18
36 | },
37 | {
38 | name: 'Thomas',
39 | scores: 90,
40 | skills: ['HTM', 'CSS', 'JS'],
41 | age: 20
42 | }
43 | ]
44 |
45 | for ({
46 | name,
47 | scores,
48 | skills,
49 | age
50 | } of users) {
51 | console.log(name, scores, skills, age)
52 | }
53 |
54 | for ({
55 | name,
56 | scores,
57 | skills,
58 | age
59 | } of users) {
60 | if (skills.length < 2) {
61 | console.log(name, scores, skills, age)
62 | }
63 | }
--------------------------------------------------------------------------------
/Day-11/level-3.js:
--------------------------------------------------------------------------------
1 | //convert object to array
2 |
3 | const students = [
4 | ['David', ['HTM', 'CSS', 'JS', 'React'],
5 | [98, 85, 90, 95]
6 | ],
7 | ['John', ['HTM', 'CSS', 'JS', 'React'],
8 | [85, 80, 85, 80]
9 | ]
10 | ]
11 |
12 |
13 | const convertArrayToObject = (arr) => {
14 | let { name, skills, scores } = arr;
15 |
16 | }
17 |
18 | const rectangle = {
19 | width: 20,
20 | height: 10,
21 | area: 200
22 | }
23 | let {
24 | width: w,
25 | heigh: h,
26 | area: a,
27 | perimeter: p
28 | } = rectangle
--------------------------------------------------------------------------------
/Day-12/level-1.js:
--------------------------------------------------------------------------------
1 | let text2 = "He earns 4000 euro from salary per month, 10000 euro annual bonus, 5500 euro online courses per month."
2 | let salaries = text2.match(/\d+/g);
3 | let totalAnnualIncome = 0;
4 | salaries.forEach(element => {
5 | totalAnnualIncome += Number(element);
6 | })
7 | console.log(totalAnnualIncome)
8 |
9 | let text = "The position of some particles on the horizontal x-axis -12, -4, -3 and -1 in the negative direction, 0 at origin, 4 and 8 in the positive direction"
10 | let sortingPoint = text2.match(/\d+/g);
11 | sortingPoint = sortingPoint.map((elements) => {
12 | return Number(elements)
13 | })
14 | const distBtwTwoPart = (arr) => {
15 | let distBtw = arr[arr.length - 1] - arr[0]
16 | return distBtw
17 | }
18 | console.log(distBtwTwoPart(sortingPoint));
19 |
20 | //to check for javascript valid variable
21 | const pattern = /[F/f]irst[Nn]ame|[F/f]irst_[Nn]ame/
22 | const isValidVariable = (str) => {
23 | console.log(pattern.test(str));
24 | }
25 | isValidVariable('first_name')
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/Day-13/level-1.js:
--------------------------------------------------------------------------------
1 | const countries = [
2 | ['Finland', 'Helsinki'],
3 | ['Sweden', 'Stockholm'],
4 | ['Norway', 'Oslo']
5 | ]
6 | console.table(countries)
7 |
8 | let countries = [{
9 | name: "nigeria",
10 | capital: "fct",
11 | population: "7billion",
12 | languages: ["hausa", "igbo", "yoruba"]
13 | },
14 | {
15 | name: "germany",
16 | capital: "munich",
17 | population: "5billion",
18 | languages: ["german"]
19 | }, {
20 | name: "italy",
21 | capital: "rome",
22 | population: "6billion",
23 | languages: ["italian", "latin"]
24 | },
25 | {
26 | name: "france",
27 | capital: "paris",
28 | population: "6billion",
29 | languages: ["french"]
30 | }
31 | ]
32 | console.table(countries)
33 |
34 |
--------------------------------------------------------------------------------
/Day-13/level-2.js:
--------------------------------------------------------------------------------
1 | //assertion message
2 | console.assert(10 > 2 * 10, "incorrect")
3 |
4 | //warning message
5 | console.warn("i'm warning you")
6 |
7 | //error message
8 | console.error("this is an error")
--------------------------------------------------------------------------------
/Day-13/level-3.js:
--------------------------------------------------------------------------------
1 | const food = ["beans", "rice", "plantain", "egg"]
2 |
3 | //while
4 | console.time("while loop")
5 | let i = 0
6 | while (i < food.length) {
7 | console.log(food[i])
8 | i++
9 | }
10 | console.timeEnd("while loop")
11 | //for
12 | console.time('Regular for loop')
13 | for (let i = 0; i < food.length; i++) {
14 | console.log(food[i])
15 | }
16 | console.timeEnd('Regular for loop')
17 | //for of
18 | console.time("for of")
19 | for (const meal of food) {
20 | console.log(meal)
21 | }
22 | console.timeEnd("for of")
23 | //forEach
24 | console.time("forEach")
25 | food.forEach(meal => console.log(meal))
26 | console.timeEnd("forEach")
27 |
28 |
29 |
--------------------------------------------------------------------------------
/Day-15/level-1.js:
--------------------------------------------------------------------------------
1 | class Animal {
2 | constructor(name, age, color, legs) {
3 | this.name = name;
4 | this.age = age;
5 | this.color = color
6 | this.legs = legs
7 | }
8 | getfullInfo() {
9 | return `${this.name} is ${this.age} year(s) old ${this.color} in color`;
10 | }
11 | set removeLegs(leg) {
12 | this.legs -= leg
13 | }
14 | get getName() {
15 | return this.name;
16 | }
17 | }
18 |
19 | let dog = new Animal("jack", 4, "brown", 4);
20 | let cat = new Animal("brie", 2, "white", 4);
21 |
22 | console.log(dog.getfullInfo());
23 | console.log(cat);
24 |
25 | class Pet extends Animal {
26 | constructor(name, age, color, legs, gender) {
27 | super(name, age, color, legs)
28 | this.gender = gender
29 | }
30 |
31 | get getGender() {
32 | return this.gender
33 | }
34 | getfullInfo() {
35 | return `${this.name} is ${this.age} year(s) old ${this.gender} ${this.color} in color`;
36 | }
37 |
38 | }
39 |
40 | let rabbit = new Pet("ross", 3, "snow-white", 4, "male")
41 | console.log(rabbit.getfullInfo());
--------------------------------------------------------------------------------
/Day-15/level-2.js:
--------------------------------------------------------------------------------
1 | class Statistics {
2 | constructor(arr) {
3 | this.arr = arr;
4 | }
5 |
6 | get length() {
7 | return this.arr.length;
8 | }
9 |
10 | count() {
11 | return this.length;
12 | }
13 |
14 | sum() {
15 | let sum = 0;
16 | this.arr.forEach((num) => {
17 | sum += num
18 | })
19 | return sum;
20 | }
21 |
22 | mean() {
23 | let sum = 0;
24 | this.arr.forEach((num) => {
25 | sum += num
26 | })
27 | return Math.ceil(sum / this.length)
28 | }
29 |
30 | min() {
31 | let minNum = this.arr[0]
32 | for (let i = 0; i < this.length; i++) {
33 | if (this.arr[i] < minNum) {
34 | minNum = this.arr[i]
35 | }
36 | }
37 | return minNum;
38 | }
39 |
40 | max() {
41 | let maxNum = this.arr[0]
42 | for (let i = 0; i < this.length; i++) {
43 | if (this.arr[i] > maxNum) {
44 | maxNum = this.arr[i]
45 | }
46 | }
47 | return maxNum
48 | }
49 |
50 | range() {
51 | return this.max() - this.min();
52 | }
53 |
54 | median() {
55 | let sorted = this.arr.sort()
56 | let index = sorted.length / 2
57 | index = Math.floor(index);
58 | return sorted[index];
59 | }
60 |
61 | mode() {
62 | return `working on it...`
63 | }
64 |
65 | variance() {
66 | let mean = this.mean()
67 | let variance = this.arr.map((num) => {
68 | return Math.pow(num - mean, 2) / this.length;
69 | })
70 | let newVariance = 0;
71 | variance.forEach(num => newVariance += num / this.length)
72 | return Math.ceil(newVariance / this.length);
73 | }
74 |
75 | standardDeviation() {
76 | return `working on it...`
77 | }
78 |
79 | frequencyDistribution() {
80 | return `working on it...`
81 | }
82 |
83 |
84 | describe() {
85 | return `
86 | Count: ${this.count()}\n
87 | Sum: ${this.sum()}\n
88 | Min: ${this.min()}\n
89 | Max: ${this.max()}\n
90 | Range: ${this.range()}\n
91 | Mean: ${this.mean()}\n
92 | Median: ${this.median()}\n
93 | Mode: ${this.mode()}\n
94 | Variance: ${this.variance()}\n
95 | Standard Deviation: ${this.standardDeviation()}\n
96 | Frequency Distribution: ${this.frequencyDistribution()}`
97 | }
98 | }
99 |
100 | let numbers = new Statistics([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]);
101 | console.log(numbers.describe())
--------------------------------------------------------------------------------
/Day-15/level-3.js:
--------------------------------------------------------------------------------
1 | class PersonAccount {
2 | constructor(firstName, lastName) {
3 | this.firstName = firstName;
4 | this.lastName = lastName;
5 | this.incomes = [];
6 | this.expenses = [];
7 | }
8 |
9 | totalIncome() {
10 | let totalIncom = 0;
11 | this.incomes.forEach(income => totalIncom += income)
12 | return totalIncom
13 | }
14 | totalExpenses() {
15 | let totalExpenses = 0;
16 | this.expenses.forEach(expense => totalExpenses += expense)
17 | return totalExpenses;
18 | }
19 |
20 | accountInfo() {
21 | return `
22 | Full-Name: ${this.firstName} ${this.lastName}
23 | total-Income: ${this.totalIncome()}
24 | total-Expenses: ${this.totalExpenses()}
25 | `
26 | }
27 |
28 | set addIncome(amount) {
29 | this.incomes.push(amount)
30 | }
31 |
32 | set addExpenses(cost) {
33 | this.expenses.push(cost)
34 | }
35 | }
36 |
37 | let myAccount = new PersonAccount("victor", "kenneth")
--------------------------------------------------------------------------------
/Day-16/level-1.js:
--------------------------------------------------------------------------------
1 | const skills = ['HTML', 'CSS', 'JS', 'React', 'Node', 'Python']
2 | const skillsTxt = JSON.stringify(skills)
3 | console.log(skillsTxt);
4 |
5 | let age = 250;
6 | const ageTxt = JSON.stringify(age)
7 | console.log(ageTxt)
8 |
9 | let isMarried = true
10 | const isMTxt = JSON.stringify(isMarried)
11 | console.log(isMTxt);
12 |
13 | const student = {
14 | firstName: 'Asabeneh',
15 | lastName: 'Yetayehe',
16 | age: 250,
17 | isMarried: true,
18 | skills: ['HTML', 'CSS', 'JS', 'React', 'Node', 'Python', ]
19 | }
20 | let studentTxt = JSON.stringify(student)
--------------------------------------------------------------------------------
/Day-16/level-2.js:
--------------------------------------------------------------------------------
1 | const student = {
2 | firstName: 'Asabeneh',
3 | lastName: 'Yetayehe',
4 | age: 250,
5 | isMarried: true,
6 | skills: ['HTML', 'CSS', 'JS', 'React', 'Node', 'Python', ]
7 | }
8 |
9 | let studentTxt = JSON.stringify(student, ['firstName', 'lastName', 'skills'])
10 | console.log(studentTxt)
--------------------------------------------------------------------------------
/Day-16/level-3.js:
--------------------------------------------------------------------------------
1 | const txt = `{
2 | "Alex": {
3 | "email": "alex@alex.com",
4 | "skills": [
5 | "HTML",
6 | "CSS",
7 | "JavaScript"
8 | ],
9 | "age": 20,
10 | "isLoggedIn": false,
11 | "points": 30
12 | },
13 | "Asab": {
14 | "email": "asab@asab.com",
15 | "skills": [
16 | "HTML",
17 | "CSS",
18 | "JavaScript",
19 | "Redux",
20 | "MongoDB",
21 | "Express",
22 | "React",
23 | "Node"
24 | ],
25 | "age": 25,
26 | "isLoggedIn": false,
27 | "points": 50
28 | },
29 | "Brook": {
30 | "email": "daniel@daniel.com",
31 | "skills": [
32 | "HTML",
33 | "CSS",
34 | "JavaScript",
35 | "React",
36 | "Redux"
37 | ],
38 | "age": 30,
39 | "isLoggedIn": true,
40 | "points": 50
41 | },
42 | "Daniel": {
43 | "email": "daniel@alex.com",
44 | "skills": [
45 | "HTML",
46 | "CSS",
47 | "JavaScript",
48 | "Python"
49 | ],
50 | "age": 20,
51 | "isLoggedIn": false,
52 | "points": 40
53 | },
54 | "John": {
55 | "email": "john@john.com",
56 | "skills": [
57 | "HTML",
58 | "CSS",
59 | "JavaScript",
60 | "React",
61 | "Redux",
62 | "Node.js"
63 | ],
64 | "age": 20,
65 | "isLoggedIn": true,
66 | "points": 50
67 | },
68 | "Thomas": {
69 | "email": "thomas@thomas.com",
70 | "skills": [
71 | "HTML",
72 | "CSS",
73 | "JavaScript",
74 | "React"
75 | ],
76 | "age": 20,
77 | "isLoggedIn": false,
78 | "points": 40
79 | },
80 | "Paul": {
81 | "email": "paul@paul.com",
82 | "skills": [
83 | "HTML",
84 | "CSS",
85 | "JavaScript",
86 | "MongoDB",
87 | "Express",
88 | "React",
89 | "Node"
90 | ],
91 | "age": 20,
92 | "isLoggedIn": false,
93 | "points": 40
94 | }
95 | }
96 | `
97 |
98 | let parsedObject = JSON.parse(txt);
99 | console.log(parsedObject)
100 | let parsedSkill = JSON.parse(txt, ["skills"])
101 | console.log(parsedSkill)
--------------------------------------------------------------------------------
/Day-17/level-1.js:
--------------------------------------------------------------------------------
1 | let profile = {
2 | firstName: "victor",
3 | lastName: "kenneth",
4 | age: 19,
5 | country: "nigeria",
6 | city: "lagos",
7 | }
8 |
9 | let txt = JSON.stringify(profile);
10 | localStorage.setItem("user", "txt");
11 |
12 |
--------------------------------------------------------------------------------
/Day-17/level-2.js:
--------------------------------------------------------------------------------
1 | let student = {
2 | firstName: "victor",
3 | lastName: "kenneth",
4 | age: 19,
5 | skills: ["html", "css", "javascript", "netlify"],
6 | country: "nigeria"
7 | }
8 |
9 | let txt = JSON.stringify(student)
10 | localStorage.setItem("s1", "txt")
--------------------------------------------------------------------------------
/Day-18/level-1.js:
--------------------------------------------------------------------------------
1 | //country api using async awaitc
2 | let countries;
3 | let languages = [];
4 | let largestCountries = [];
5 | // largestCountries.length = 10;
6 | const url = 'https://restcountries.eu/rest/v2/all'
7 | const fetchData = async () => {
8 | try {
9 | const response = await fetch(url)
10 | const data = await response.json()
11 | countries = data;
12 | //logging the country name,capital,languages,population
13 | countries.forEach(country => {
14 | console.log(`country:${country.name} capital:${country.capital} languages:${country.languages} population${country.population}`)
15 | })
16 |
17 | //total number of languages in the world;
18 | countries.forEach(country => {
19 | country.languages.forEach(language => {
20 | if (languages.indexOf(language.name) === -1) {
21 | languages.push(language.name)
22 | }
23 | })
24 | })
25 |
26 | //largest countries
27 | let highestCountry = 0;
28 |
29 | countries.forEach(country => {
30 | if (country.area >= highestCountry) {
31 | highestCountry = country.area;
32 | largestCountries.push(country)
33 | }
34 | })
35 | console.log(`the total number of languages in the world is ${languages.length}`)
36 | } catch (err) {
37 | console.log(err)
38 | }
39 | }
40 | console.log('===== async and await')
41 | fetchData();
42 |
43 | // countries.forEach(country => {
44 | // console.log(`country:${country.name} capital:${country.capital} languages:${country.languages} population${population}`)
45 | // })
46 |
47 | //cat api using promise
48 | let catNames = [];
49 | let cats = []
50 | const catsAPI = 'https://api.thecatapi.com/v1/breeds'
51 | fetch(catsAPI)
52 | .then(response => response.json())
53 | .then(data => {
54 | data.forEach(cat => {
55 | cat.push(cat);
56 | })
57 | })
58 | .catch(error => console.log(error))
59 |
60 | if (catNames) {
61 | cats.forEach(cat => {
62 | catNames.push(cat.name)
63 | })
64 | console.log(catNames)
65 | }
--------------------------------------------------------------------------------
/Day-19/level-1.js:
--------------------------------------------------------------------------------
1 | //closure with one inner function
2 | function outerFunction() {
3 | let count = 0;
4 |
5 | function innerFunction() {
6 | count++
7 | return count
8 | }
9 |
10 | return innerFunction
11 | }
12 |
13 | //with three inner function
14 | function outerFunction() {
15 | let count = 0;
16 |
17 | function plusOne() {
18 | count++
19 | return count
20 | }
21 |
22 | function minusOne() {
23 | count--
24 | return count
25 | }
26 |
27 | return {
28 | plusOne: plusOne(),
29 | minusOne: minusOne()
30 | }
31 | }
32 |
33 | //personAccount
34 |
35 | function personAccount() {
36 | let firstName = "victor";
37 | let lastName = "kenneth";
38 | let incomes = [1000, 300];
39 | let expenses = [500];
40 |
41 | function addIncome(income) {
42 | incomes.push(income)
43 | return income;
44 | }
45 |
46 | function addExpense(expense) {
47 | expenses.push(expense);
48 | return expenses;
49 | }
50 |
51 | function totalIncome() {
52 | let TI = 0;
53 | let TE = 0;
54 | incomes.forEach(income => {
55 | TI += income
56 | })
57 | expenses.forEach(expense => {
58 | TE += expense
59 | })
60 |
61 | let result = TI - TE;
62 | return result;
63 | }
64 |
65 | function totalExpense() {
66 | let TE = 0;
67 | expenses.forEach(expense => {
68 | TE += expense
69 | })
70 | return TE
71 | }
72 |
73 | function accountBalance() {
74 | totalIncome();
75 | }
76 |
77 | function accountInfo() {
78 | return `name:${firstName} ${lastName} Balance:${totalIncome()}`
79 | }
80 |
81 | return {
82 | addIncome: addIncome(),
83 | addExpense: addExpense(),
84 | totalIncome: totalIncome(),
85 | totalExpense: totalExpense(),
86 | accountBalance: accountBalance(),
87 | accountInfo: accountInfo()
88 | }
89 | }
90 |
91 | const accFunc = personAccount();
92 | console.log(accFunc.accountInfo);
--------------------------------------------------------------------------------
/Day-2/arithmetic-operators.js:
--------------------------------------------------------------------------------
1 | let operandOne = 4;
2 | let operandTwo = 3;
3 | console.log(operandOne + operandTwo);
4 | console.log(operandOne - operandTwo);
5 | console.log(operandOne * operandTwo);
6 | console.log(operandOne / operandTwo);
7 | console.log(operandOne % operandTwo);
8 | console.log(operandOne ** operandTwo);
9 | console.log(operandOne++);
10 | console.log(operandTwo--);
11 |
12 |
--------------------------------------------------------------------------------
/Day-2/booleans-part.js:
--------------------------------------------------------------------------------
1 | let truthy = [true, 1, "victor"];
2 | let falsy = [false,undefined,null]
--------------------------------------------------------------------------------
/Day-2/strings-part.js:
--------------------------------------------------------------------------------
1 | let name = "30 Days Of JavaSscript"
2 | console.log(name);
3 | console.log(name.length);
4 | console.log(name.toUpperCase());
5 | console.log(name.toLowerCase());
6 | console.log(name.substr(0, 1));
7 | console.log(name.slice(3));
8 | let s = "You cannot end a sentence with because because because is a conjunction";
9 | console.log(name.substr(30, 23));
10 | console.log(name.includes("Script"));
11 | console.log(name.split(""));
12 | console.log(name.split(" "));
13 | let techComp = "Facebook,Google,Microsoft,Apple,IBM,Oracle,Amazon"
14 | console.log(techComp.split(","));
15 | console.log(name.replace("JavaScript", "Python"));
16 | console.log(name.charCodeAt("J"));
17 | console.log(name.indexOf("a"));
18 | console.log(name.lastIndexOf("a"));
19 | let sent = "You cannot end a sentence with because because because is a conjunction";
20 | console.log(sent.indexOf("because"))
21 | console.log(sent.search("because"));
22 | console.log(name.trim());
23 | console.log(name.startsWith("3"));
24 | console.log(name.endsWith("t"));
25 | console.log(name.match("a"));
26 | console.log(s.match("a"));
27 | let conc = "30 Days Of "
28 | console.log(conc.concat("JavaScript"));
29 | console.log(name.repeat(2));
30 | let text = "Love is the best thing in this world.Some found their love and some are still looking for their love";
31 | console.log(text.search("love"));
32 | let text2 = "He earns 5000 euro from salary per month, 10000 euro annual bonus, 15000 euro online courses per month."
33 | let salaries = text2.match(/\d+/g);
34 | let totalAnnualIncome = 0;
35 | salaries.forEach(element => {
36 | totalAnnualIncome += Number(element);
37 | })
38 | console.log(totalAnnualIncome
39 | )
40 | const sentence = '%I $am@% a %tea@cher%, &and& I lo%#ve %tea@ching%;. There $is nothing; &as& mo@re rewarding as educa@ting &and& @emp%o@wering peo@ple. ;I found tea@ching m%o@re interesting tha@n any other %jo@bs. %Do@es thi%s mo@tivate yo@u to be a tea@cher!? %Th#is 30#Days&OfJavaScript &is also $the $result of &love& of tea&ching'
41 | console.log(sentence.replace(/[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, ''));
42 | let fName = "victor";
43 | let lName = "kenneth";
44 | let country = "nigeria";
45 | let city = "lagos";
46 | let age = 19;
47 | let isMarried = false
48 | let year = 2020;
49 | let vars = [fName, lName, country, city, age, isMarried, year, name, s, conc, techComp, sent, text, salaries, totalAnnualIncome, sentence];
50 | vars.forEach(element => {
51 | console.log(typeof element);
52 | })
--------------------------------------------------------------------------------
/Day-21/level-1/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Document
7 |
8 |
9 | victor
10 | chioma
11 | henderson
12 | van dijk
13 |
14 |
15 |
--------------------------------------------------------------------------------
/Day-21/level-1/script.js:
--------------------------------------------------------------------------------
1 | //get by id;
2 | const firstP = document.getElementsByTagName("p")[0];
3 | console.log(firstP)
4 |
5 | //get by id
6 | const one = document.querySelector("#one");
7 | const two = document.querySelector("#two");
8 | const three = document.querySelector("#three");
9 | const four = document.querySelector("#four");
10 | console.log(one)
11 | console.log(two)
12 | console.log(three)
13 | console.log(four)
14 |
15 | //get all the p as nodeList
16 | let pS = document.querySelectorAll('p');
17 | // pS = Array.from(pS)
18 | console.groupCollapsed(pS)
19 |
20 | pS.forEach(p => {
21 | console.log(p.textContent)
22 | })
23 |
24 | pS[3].textContent = "fourth paragraph"
25 |
26 | pS[0].className = "first-pararaph";
27 | pS[0].id = "first";
28 | //setAttribute
29 | pS[1].setAttribute("class", "second");
30 | pS[1].setAttribute("id", "second");
31 | //adding a class to another class
32 | pS[2].classList.add('title', 'third')
--------------------------------------------------------------------------------
/Day-21/level-2/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Document
7 |
8 |
9 | victor
10 | chioma
11 | henderson
12 | van dijk
13 |
14 |
15 |
--------------------------------------------------------------------------------
/Day-21/level-2/script.js:
--------------------------------------------------------------------------------
1 | let ps = document.querySelectorAll('p');
2 | for (let i = 0; i < ps.length; i++) {
3 | if (i % 2 == 0) {
4 | ps[i].style.color = 'green'
5 | } else {
6 | ps[i].style.color = 'red'
7 | }
8 | }
--------------------------------------------------------------------------------
/Day-21/level-3/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | JavaScript for Everyone:DOM
6 |
7 |
8 |
9 |
Asabeneh Yetayeh challenges in 2020
10 |
30DaysOfJavaScript Challenge
11 |
12 |
13 | - 30DaysOfPython Challenge Done
14 | - 30DaysOfJavaScript Challenge Ongoing
15 | - 30DaysOfReact Challenge Coming
16 | - 30DaysOfFullStack Challenge Coming
17 | - 30DaysOfDataAnalysis Challenge Coming
18 | - 30DaysOfReactNative Challenge Coming
19 | - 30DaysOfMachineLearning Challenge Coming
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/Day-21/level-3/script.js:
--------------------------------------------------------------------------------
1 | const body = document.querySelector("body")
2 | const h1 = document.querySelector('h1');
3 | const h2 = document.querySelector('h2');
4 | const p = document.querySelector("p");
5 | const lis = document.querySelectorAll("li")
6 |
7 | //body styling
8 | body.style.textAlign = "center"
9 | body.style.fontFamily = "sans-serif"
10 |
11 | //h1 chameleon styling
12 | h1.innerHTML = `Asabeneh Yetayeh challenges in 2020`
13 | let year = document.querySelector("#year");
14 | let color;
15 | const chameleon = () => {
16 | let random1 = Math.floor(Math.random() * 255)
17 | let random2 = Math.floor(Math.random() * 255)
18 | let random3 = Math.floor(Math.random() * 255)
19 | color = `rgb(${random1},${random2},${random3})`
20 | year.style.color = color;
21 | }
22 | setInterval(chameleon, 1000)
23 |
24 | //h2 decoration
25 | h2.style.textDecoration = "underline"
26 |
27 | p.textContent = Date();
28 | p.style.border = "solid"
29 | p.style.width = "300px";
30 | p.style.margin = "0 auto"
31 | //body.appendChild(p)
32 | //headColor()
33 | const chameleon2 = () => {
34 | let random1 = Math.floor(Math.random() * 255)
35 | let random2 = Math.floor(Math.random() * 255)
36 | let random3 = Math.floor(Math.random() * 255)
37 | color = `rgb(${random1},${random2},${random3})`
38 | // year.style.color = color;
39 | p.style.backgroundColor = color;
40 | }
41 | setInterval(chameleon2, 1000)
42 |
43 | lis.forEach(li => {
44 | li.style.listStyle = "none";
45 | li.style.border = "solid";
46 | li.style.margin = "0 auto"
47 | li.style.width = "650px";
48 | li.style.height = "40px"
49 | if (li.textContent.toLowerCase().includes("done")) {
50 | li.style.backgroundColor = "green"
51 | } else if (li.textContent.toLowerCase().includes("ongoing")) {
52 | li.style.backgroundColor = "yellow"
53 | } else {
54 | li.style.backgroundColor = "red"
55 | }
56 | });
--------------------------------------------------------------------------------
/Day-22/level-1/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Number-Generator
7 |
29 |
30 |
31 | Number Generator
32 | 30DaysOfJavaScript Dom Day2
33 | Author:Victor Kenneth
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/Day-22/level-1/script.js:
--------------------------------------------------------------------------------
1 | let body = document.querySelector("body")
2 | let div = document.querySelector("div")
3 | for (let i = 0; i <= 100; i++) {
4 | if (i % 2 === 0) {
5 | let box = document.createElement("div")
6 | box.textContent = i
7 | box.style.width = "150px";
8 | box.style.height = "120px"
9 | box.style.backgroundColor = "green"
10 | box.style.margin = "8px";
11 | div.appendChild(box)
12 | } else {
13 | let box = document.createElement("div")
14 | box.textContent = i;
15 | box.style.width = "150px";
16 | box.style.height = "120px";
17 | box.style.backgroundColor = "yellow"
18 | box.style.margin = "8px";
19 | div.appendChild(box)
20 | }
21 | }
--------------------------------------------------------------------------------
/Day-22/level-2/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Number-Generator
7 |
29 |
30 |
31 | Number Generator
32 | 30DaysOfJavaScript Dom Day2
33 | Author:Victor Kenneth
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/Day-22/level-2/script.js:
--------------------------------------------------------------------------------
1 | let div = document.querySelector("div")
2 |
3 | const url = 'https://restcountries.eu/rest/v2/all'
4 | const fetchData = async () => {
5 | try {
6 | const response = await fetch(url)
7 | const data = await response.json()
8 | countries = data;
9 | //logging the country name,capital,languages,population
10 | countries.forEach(country => {
11 | if (country.name.toLowerCase() === "nigeria") {
12 | let box = document.createElement("div")
13 | box.textContent = country.name
14 | box.style.width = "150px";
15 | box.style.height = "120px"
16 | box.style.backgroundColor = "green"
17 | box.style.margin = "8px";
18 | div.appendChild(box)
19 | }
20 | let box = document.createElement("div")
21 | box.textContent = country.name
22 | box.style.width = "150px";
23 | box.style.height = "120px"
24 | box.style.backgroundColor = "aqua"
25 | box.style.margin = "8px";
26 | div.appendChild(box)
27 | })
28 |
29 | } catch (err) {
30 | console.log(err)
31 | }
32 | }
33 | console.log('===== async and await')
34 | fetchData();
--------------------------------------------------------------------------------
/Day-23/level-1/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Number-Generator
7 |
42 |
43 |
44 | Number Generator
45 | 30DaysOfJavaScript Dom Day2
46 | Author:Victor Kenneth
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
--------------------------------------------------------------------------------
/Day-23/level-1/script.js:
--------------------------------------------------------------------------------
1 | let body = document.querySelector("body")
2 | let input = document.querySelector("input")
3 | let button = document.querySelector("button")
4 | let message = document.querySelector(".warning-message")
5 | let div = document.querySelector(".container")
6 | console.log(message)
7 | button.addEventListener("click", function () {
8 | let val = input.value;
9 | if (typeof (Number(val)) === "number" && Number(val) > 0) {
10 | div.innerHTML = "";
11 | input.value = ""
12 | message.innerHTML = "";
13 | for (let i = 0; i <= val; i++) {
14 | if (i % 2 === 0) {
15 | let box = document.createElement("div")
16 | box.textContent = i
17 | box.style.width = "150px";
18 | box.style.height = "120px"
19 | box.style.backgroundColor = "green"
20 | box.style.margin = "8px";
21 | div.appendChild(box)
22 | } else {
23 | let box = document.createElement("div")
24 | box.textContent = i;
25 | box.style.width = "150px";
26 | box.style.height = "120px";
27 | box.style.backgroundColor = "yellow"
28 | box.style.margin = "8px";
29 | div.appendChild(box)
30 | }
31 | }
32 | } else if (val.length === 0) {
33 | div.innerHTML = ""
34 | input.value = "";
35 | message.innerHTML = "";
36 | message.textContent = "enter a number to generate numbers";
37 | message.style.color = "red"
38 | } else if (typeof (val) === "string") {
39 | div.innerHTML = "";
40 | input.value = "";
41 | message.innerHTML = "";
42 | message.textContent = "please enter number values only";
43 | message.style.color = "red"
44 | }
45 | })
--------------------------------------------------------------------------------
/Day-23/level-2/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Document
7 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
--------------------------------------------------------------------------------
/Day-23/level-2/script.js:
--------------------------------------------------------------------------------
1 | let body = document.querySelector("body");
2 | let keyName = document.querySelector(".key");
3 | let keyCode = document.querySelector(".key-code");
4 | let input = document.querySelector("input")
5 | console.log("hiii")
6 | // body.addEventListener("keypress", function (e) {
7 | // keyCode.innerHTML = ""
8 | // keyName.innerHTML = ""
9 | // keyName.innerHTML = e.keyName;
10 | // console.log(e.keyCode)
11 | // console.log(e.keyName)
12 | // keyCode.innerHTML = e.keyCode;
13 | // });
14 | body.addEventListener("keydown", function (e) {
15 | keyCode.innerHTML = ""
16 | keyName.innerHTML = ""
17 | let keyMessage = `you pressed ${e.key}
`
18 | keyName.innerHTML = keyMessage;
19 | let keyCodeMessage = `${e.keyCode}
`
20 | keyCode.innerHTML = keyCodeMessage;
21 | });
--------------------------------------------------------------------------------
/Day-24/level-1/app.js:
--------------------------------------------------------------------------------
1 | const space = {
2 | mercury:{
3 | gravity:0.38,
4 | image:"mercury.png"
5 | },
6 | venus:{
7 | gravity:0.91,
8 | image:"venus.png"
9 | },
10 | earth:{
11 | gravity:1.0,
12 | image:"earth.png"
13 | },
14 | mars:{
15 | gravity:0.38,
16 | image:"mars.png"
17 | },
18 | jupiter:{
19 | gravity:2.34,
20 | image:"jupiter.png"
21 | },
22 | saturn:{
23 | gravity:0.93,
24 | image:"saturn.png"
25 | },
26 | uranus:{
27 | gravity:0.92,
28 | image:"uranus.png"
29 | },
30 | neptune:{
31 | gravity:1.12,
32 | image:"neptune.png"
33 | }
34 | }
35 |
36 | const input = document.querySelector("input");
37 | const select = document.querySelector("select");
38 | const button = document.querySelector("button")
39 | const container = document.querySelector(".container");
40 | let weight;
41 |
42 | const containerUI = (img,text) => {
43 | let image = document.createElement("img");
44 | image.src = `images/${img}`;
45 | let p = document.createElement("p");
46 | p.textContent = text;
47 | p.className = "big"
48 | container
49 | container.appendChild(image);
50 | container.appendChild(p);
51 | // container.className = "container-border"
52 | }
53 |
54 | button.addEventListener("click",function(){
55 | let imgSrc;
56 | container.innerHTML = "";
57 | imgSrc = space[select.value].image;
58 | weight = Number(input.value) * space[select.value].gravity;
59 | containerUI(imgSrc,weight);
60 | console.log(weight)
61 | })
--------------------------------------------------------------------------------
/Day-24/level-1/images/earth.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/3KINGZ/30-Days-of-JavaScript-Solutions/9577eace2fa1b5bbf1fecd187e79a9e3244d4ee6/Day-24/level-1/images/earth.png
--------------------------------------------------------------------------------
/Day-24/level-1/images/galaxy.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/3KINGZ/30-Days-of-JavaScript-Solutions/9577eace2fa1b5bbf1fecd187e79a9e3244d4ee6/Day-24/level-1/images/galaxy.gif
--------------------------------------------------------------------------------
/Day-24/level-1/images/jupiter.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/3KINGZ/30-Days-of-JavaScript-Solutions/9577eace2fa1b5bbf1fecd187e79a9e3244d4ee6/Day-24/level-1/images/jupiter.png
--------------------------------------------------------------------------------
/Day-24/level-1/images/mars.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/3KINGZ/30-Days-of-JavaScript-Solutions/9577eace2fa1b5bbf1fecd187e79a9e3244d4ee6/Day-24/level-1/images/mars.png
--------------------------------------------------------------------------------
/Day-24/level-1/images/mercury.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/3KINGZ/30-Days-of-JavaScript-Solutions/9577eace2fa1b5bbf1fecd187e79a9e3244d4ee6/Day-24/level-1/images/mercury.png
--------------------------------------------------------------------------------
/Day-24/level-1/images/moon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/3KINGZ/30-Days-of-JavaScript-Solutions/9577eace2fa1b5bbf1fecd187e79a9e3244d4ee6/Day-24/level-1/images/moon.png
--------------------------------------------------------------------------------
/Day-24/level-1/images/neptune.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/3KINGZ/30-Days-of-JavaScript-Solutions/9577eace2fa1b5bbf1fecd187e79a9e3244d4ee6/Day-24/level-1/images/neptune.png
--------------------------------------------------------------------------------
/Day-24/level-1/images/pluto.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/3KINGZ/30-Days-of-JavaScript-Solutions/9577eace2fa1b5bbf1fecd187e79a9e3244d4ee6/Day-24/level-1/images/pluto.png
--------------------------------------------------------------------------------
/Day-24/level-1/images/saturn.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/3KINGZ/30-Days-of-JavaScript-Solutions/9577eace2fa1b5bbf1fecd187e79a9e3244d4ee6/Day-24/level-1/images/saturn.png
--------------------------------------------------------------------------------
/Day-24/level-1/images/uranus.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/3KINGZ/30-Days-of-JavaScript-Solutions/9577eace2fa1b5bbf1fecd187e79a9e3244d4ee6/Day-24/level-1/images/uranus.png
--------------------------------------------------------------------------------
/Day-24/level-1/images/venus.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/3KINGZ/30-Days-of-JavaScript-Solutions/9577eace2fa1b5bbf1fecd187e79a9e3244d4ee6/Day-24/level-1/images/venus.png
--------------------------------------------------------------------------------
/Day-24/level-1/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Document
7 |
8 |
43 |
44 | Calculate the weight of an object on a planet
45 |
46 |
47 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
--------------------------------------------------------------------------------
/Day-3/arithmetic-operators.js:
--------------------------------------------------------------------------------
1 | //area of a triangle
2 | let base = Number(prompt("enter base of the triangle"));
3 | let height = Number(prompt("enter height of the triangle"));
4 | let area = 0.5 * base * height;
5 | console.log(`the area of the triangle is ${area}`);
6 |
7 | //perimeter of a triangle
8 | let sideA = Number(prompt("enter side A of the triangle"));
9 | let sideB = Number(prompt("enter side B of the triangle"));
10 | let sideC = Number(prompt("enter side C of the triangle"));
11 | let perimeter = sideA + sideB + sideC;
12 | console.log(`the perimeter of the triangle is ${perimeter}`)
13 |
14 | //area and perimeter of a rectangle
15 | let length = Number(prompt("enter length of the rectangle"));
16 | let width = Number(prompt("enter width of the rectangle"));
17 | let areaOfRectangle = length * width;
18 | let perimeterOfRectangle = 2 * (length + width);
19 | console.log(`the area of the rectangle is ${areaOfRectangle} while the perimeter is ${perimeterOfRectangle}`)
20 |
21 | //area and circumference of a circle
22 | const pi = 3.14
23 | let radius = Number(prompt("enter radius of a circle"));
24 | let areaOfCircle = pi * radius * radius;
25 | let circumference = 2 * pi * radius;
26 | console.log(`the area of the circle is ${areaOfCircle} while the circumference is ${circumference}`)
27 |
28 | //pay of a person
29 | let hours = Number(prompt("enter your hours"));
30 | let rate = Number(prompt("enter your rate"));
31 | let pay = hours * rate;
32 | console.log(`your pay is ${pay}`)
33 |
34 | //number of seconds a person has live
35 | let secondsInseconds = 60;
36 | let secondsInHour = secondsInseconds * 60;
37 | let secondsInDay = secondsInHour * 24;
38 | let secondsInYear = secondsInDay * 365;
39 | let yearsLive = Number(prompt("how many years have you live?"));
40 | let secondsOld = yearsLive * secondsInYear;
41 | console.log(`you are ${secondsOld} seconds olds`)
42 |
43 | //truthy and falsy
44 | let truthy = [true, "victor", 3];
45 | let falsy = [false, undefined, null];
46 |
47 | //ternary operator
48 | const firstName = "victor"
49 | const lastName = "kenneth"
50 | firstName.length > lastName.length ? console.log(`your first Name is greater than your family name`) : console.log(`your last name is greater than your name`);
51 |
52 | //allowed to drive
53 | let age = Number(prompt("what is your age"));
54 | if (age > 18) {
55 | console.log("you are allowed to drive");
56 | } else {
57 | console.log(`you are ${age}, you will be allowed to drive after ${18 - age} years`)
58 | }
59 |
60 | //time object
61 | let date = new Date();
62 | console.log(`year:${date.getFullYear()}`);
63 | console.log(`year:${date.getMonth()}`);
64 | console.log(`year:${date.getDate()}`);
65 | console.log(`year:${date.getDay()}`);
66 | console.log(`year:${date.getHours()}`)
67 | console.log(`year:${date.getMinutes()}`)
68 | console.log(`year:${date.getSeconds()}`);
69 | let YYYMMDD = `${date.getFullYear()}-${date.getMonth()}-${date.getDate()} ${date.getHours()}-${date.getMinutes()}-${date.getSeconds()}`
70 | let DDMMYYYY = `${date.getDate()}-${date.getMonth()}-${date.getFullYear()} ${date.getHours()}-${date.getMinutes()}-${date.getSeconds()}`
71 | let DdMmYYy = `${date.getDate()}/${date.getMonth()}/${date.getFullYear()} ${date.getHours()}-${date.getMinutes()}-${date.getSeconds()}`
72 | console.log(YYYMMDD);
73 | console.log(DDMMYYYY);
74 | console.log(DdMmYYy);
--------------------------------------------------------------------------------
/Day-3/data-types.js:
--------------------------------------------------------------------------------
1 | const firstName = "victor"
2 | const lastName = "kenneth"
3 | const country = "Nigeria"
4 | const city = "lagos"
5 | const age = 19;
6 | const isMarried = false;
7 | const year = new Date().getFullYear();
8 |
9 | let vars = [firstName, lastName, country, city, age, isMarried, year];
10 | vars.forEach(function (element) {
11 | console.log(typeof element);
12 | });
13 |
14 | console.log("10" === 10)
15 | console.log(parseInt(9.8) === 10);
--------------------------------------------------------------------------------
/Day-4/conditionals.js:
--------------------------------------------------------------------------------
1 | let age = Number(prompt("enter age"));
2 | if (age > 18) {
3 | console.log("you are old enough to drive")
4 | } else {
5 | console.log(`you are left with ${18-age} year(s) to drive`)
6 | }
7 |
8 | let yourAge = 30;
9 | if (age > yourAge) {
10 | console.log("i'm older than you with ${age - yourAge}")
11 | } else {
12 | console.log(`you are ${yourAge - age} years older than me`)
13 | }
14 |
15 | let a = 4;
16 | let b = 3;
17 | if (a > b) {
18 | console.log("a is greater than b");
19 | } else {
20 | console.log("a is less than b");
21 |
22 | }
23 | //ternary
24 | (a > b) ? console.log("a is greater than b"): console.log("a is less than b");
25 |
26 | let score = Number(prompt("enter your score"));
27 | switch (true) {
28 | case score > 80:
29 | console.log("A");
30 | break;
31 | case score > 70:
32 | console.log("B");
33 | break;
34 | case score > 60:
35 | console.log("C");
36 | break;
37 | case score > 50:
38 | console.log("D");
39 | break;
40 | case (score < 50):
41 | console.log("F");
42 | break;
43 | default:
44 | console.log("no score assigned")
45 | }
46 |
47 |
48 | //seasons
49 | let month = prompt("enter month to check seasons");
50 | switch (month) {
51 | case "september":
52 | case "october":
53 | case "November":
54 | console.log("the season is Autumn");
55 | break;
56 | case "december":
57 | case "january":
58 | case "febuary":
59 | console.log("the season is Winter");
60 | break;
61 | case "march":
62 | case "april":
63 | case "may":
64 | console.log("the season is Spring");
65 | break;
66 | case "june":
67 | case "july":
68 | case "august":
69 | console.log("the season is Summer");
70 | break;
71 | default:
72 | console.log("invalid Month")
73 | }
74 |
75 | //even and odd
76 | let num = Number(prompt("enter number to kno if it's even/odd"))
77 | if (num % 2 === 0) {
78 | console.log(`${num} is an even number`)
79 | } else if (num % 2 !== 0) {
80 | console.log(`${num} is an odd number`)
81 | }
82 |
83 | //check weekend
84 | let weekDay = prompt("enter weekDay to check if it's a weekend")
85 | if (weekDay == "saturday" || weekDay == "sunday") {
86 | console.log(`${weekDay} is a weekend day`)
87 | } else if (weekDay == "monday" || weekDay == "tuesday" || weekDay == "wednesday" || weekDay == "thursday" || weekDay == "friday") {
88 | console.log(`${weekDay} is a work day`)
89 | } else {
90 | console.log("invalid weekDay")
91 | }
92 |
93 | //checkDays in month
94 | let month = prompt("enter month to check number of days");
95 | switch (month) {
96 | case "january":
97 | case "march":
98 | case "may":
99 | case "july":
100 | case "august":
101 | case "october":
102 | case "december":
103 | console.log(`${month} has 31 days`)
104 | break;
105 | case "april":
106 | case "june":
107 | case "september":
108 | case "november":
109 | console.log(`${month} has 30 days`)
110 | break;
111 | case "febuary":
112 | console.log(`${month} has 29 days`)
113 | break;
114 | default:
115 | console.log("invalid month entered");
116 | }
--------------------------------------------------------------------------------
/Day-5/array.js:
--------------------------------------------------------------------------------
1 | let food = ["rice", "plantain", "beans", "yam", "indomie"];
2 | console.log(food.length);
3 | let firstItem = console.log(food[0]);
4 | let middleItem = console.log(food[3]);
5 | let lastItem = console.log(food[food.length - 1]);
6 |
7 | let mixedDataType = ["victor", 19, true, null, {
8 | favoriteFood: ["beans", "plantain", "rice and stew"]
9 | }, undefined]
10 |
11 | let techCompanies = ["google", "microsoft", "oracle", "amazon", "ibm", "oracle", "apple"];
12 | console.log(techCompanies);
13 | console.log(techCompanies.length);
14 | console.log(techCompanies[0]);
15 | console.log(techCompanies[4]);
16 | console.log(techCompanies[techCompanies.length - 1]);
17 | let searchTechComp = prompt("enter company to search");
18 | if (techCompanies.includes(searchTechComp)) {
19 | console.log(searchTechComp)
20 | } else {
21 | console.log("company not found")
22 | }
23 |
24 | let oo = []
25 | for (let i = 0; i < techCompanies.length; i++) {
26 | oo.push(techCompanies[i].includes("oo"));
27 | }
28 | techCompanies.sort();
29 | techCompanies.reverse();
30 | techCompanies.slice(0, 3);
31 | techCompanies.slice(techCompanies.length - 1, 3)
32 | techCompanies.slice(Math.floor(techCompanies.length / 2), 1);
33 | techCompanies.pop();
34 | techCompanies.length = 0;
35 |
36 | let text = "I love teaching and empowering people. I teach HTML, CSS, JS, React, Python."
37 | text.split("");
38 | console.log(text.length);
39 |
40 | let shoppingCart = ["milk", "coffee", "tea", "honey"]
41 | shoppingCart.unshift("meat");
42 | shoppingCart.push("sugar");
43 | shoppingCart[shoppingCart.indexOf("tea")] = "green tea";
44 |
45 | let frontend = ['HTML', 'CSS', 'JS', 'React', 'Redux'];
46 | let backend = ['Node', 'Express', 'MongoDB'];
47 | console.log(frontend.concat(backend));
48 |
49 | let ages = [19, 22, 19, 24, 20, 25, 26, 24, 25, 24];
50 | let minAge = ages.sort()[0];
51 | let maxAge = ages.sort()[ages.length - 1];
52 | console.log(minAge);
53 | console.log(maxAge);
54 | let medianAge = ages[Math.floor(ages.length / 2)];
55 | console.log(medianAge);
56 | let avgAge;
57 | for (i = 0; i < ages.length; i++) {
58 | let totalAge = 0;
59 | totalAge += ages[i];
60 | avgAge = totalAge / ages.length;
61 | }
62 | console.log(avgAge)
63 | let range = maxAge - minAge;
64 | console.log(range);
65 | let ma = abs(minAge - avgAge);
66 | let maa = abs(maxAge - avgAge);
67 | console.log(ma);
68 | console.log(maa);
69 |
--------------------------------------------------------------------------------
/Day-5/countries.js:
--------------------------------------------------------------------------------
1 | let countries = ["nigeria", "U.S.A", "italy", "canada", "lebanon"];
--------------------------------------------------------------------------------
/Day-5/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Array
8 |
9 |
10 | Array
11 | countries
12 |
13 |
14 |
15 | web technologies
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/Day-5/main.js:
--------------------------------------------------------------------------------
1 | console.log(countries);
2 | console.log(webTechs);
3 |
4 | if (countries.includes("ethiopia")) {
5 | console.log("ETHIOPIA")
6 | } else {
7 | countries.push("ethipia");
8 | }
9 |
10 | if (webTechs.includes("sass")) {
11 | console.log("sass is a preprocessor")
12 | } else {
13 | webTechs.push("sass");
14 | }
15 |
16 | countries.forEach(function (country) {
17 | let p = document.createElement("p");
18 | p.textContent = country;
19 | document.querySelector("#countries").appendChild(p);
20 | })
21 |
22 | webTechs.forEach(function (webTech) {
23 | let p = document.createElement("p");
24 | p.textContent = webTech;
25 | document.querySelector("#web-technologies").appendChild(p);
26 | })
27 |
28 | let middleCountry = document.createElement("p");
29 | middleCountry.textContent = `the middle country is ${countries[countries.length / 2]}`
30 |
31 | if (countries.length % 2 === 0) {
32 | let a = countries.length / 2;
33 | console.log(countries.slice(0, a));
34 | console.log(countries.slice(a + 1,countries.length -1))
35 | } else {
36 | countries.push("korea");
37 | let b = countries.length / 2;
38 | console.log(countries.slice(0, b));
39 | console.log(countries.slice(b + 1, countries.length - 1))
40 | }
--------------------------------------------------------------------------------
/Day-5/webtech.js:
--------------------------------------------------------------------------------
1 | let webTechs = ["html", "css", "javascript", "vue", "react", "mongodb", "angular"]
--------------------------------------------------------------------------------
/Day-6/loops.js:
--------------------------------------------------------------------------------
1 | //loop 0-10
2 | //for-loop
3 | for (let i = 0; i <= 10; i++) {
4 | console.log(i);
5 | }
6 |
7 | //while-loop
8 | let i = 0;
9 | while (i < 10) {
10 | i++;
11 | console.log(i);
12 | }
13 |
14 | //do-while
15 | let i = 0;
16 | do {
17 | i++;
18 | console.log(i)
19 | } while (i < 10)
20 |
21 |
22 | //loop 10-0
23 | //for-loop
24 | for (let i = 10; i <= 10; i--) {
25 | console.log(i);
26 | }
27 |
28 | //while-loop
29 | let i = 10;
30 | while (i > 0) {
31 | i--;
32 | console.log(i)
33 | }
34 |
35 | //do-while loop
36 | let i = 10;
37 | do {
38 | i--;
39 | console.log(i)
40 | } while (i > 0)
41 |
42 | let n = Number(prompt("enter number"));
43 | for (let i = 0; i <= n; i++) {
44 | console.log(i);
45 | }
46 |
47 | let str = "";
48 | for (let i = 0; i < 7; i++) {
49 | str += "#";
50 | console.log(str)
51 | }
52 |
53 | //multiplication
54 | for (let i = 0; i <= 10; i++) {
55 | console.log(`${i} x ${i} = ${i * i}`)
56 | }
57 |
58 | //power of 2,3
59 | for (let i = 0; i <= 10; i++) {
60 | console.log(`${i} ${i ** 2} ${i ** 3}`)
61 | }
62 |
63 | //print even numbers from 0-100;
64 | for (i = 0; i <= 100; i++) {
65 | if (i % 2 == 0) {
66 | console.log(i)
67 | }
68 | }
69 |
70 | //print odd numbers
71 | for (i = 0; i <= 100; i++) {
72 | if (i % 2 > 0) {
73 | console.log(i)
74 | }
75 | }
76 |
77 | //print prime numbers
78 | for (let i = 0; i <= 100; i++) {
79 | for (let k = 2; k < i; k++) {
80 | if (i % k === 0 && i > 1) {
81 | console.log(i)
82 | }
83 | }
84 | }
85 |
86 | //sum of all numbers
87 | let sum = 0;
88 | for (let i = 0; i <= 100; i++) {
89 | sum += i;
90 | }
91 | console.log(sum)
92 |
93 | //sum of all even and odd
94 | let even = 0;
95 | let odd = 0;
96 | for (let i = 0; i <= 100; i++) {
97 | if (i % 2 == 0) {
98 | even += i;
99 | } else if (i % 2 > 0) {
100 | odd += i
101 | }
102 | }
103 | console.log(`the sum of all even number is ${even}. And the sum of all odd numbers is ${odd}`)
104 |
105 | //storing sum of all even/odd numbers in an array
106 | let sumEvenOdd = [0, 0]
107 | for (let i = 0; i <= 100; i++) {
108 | if (i % 2 == 0) {
109 | sumEvenOdd[0] += i;
110 | } else if (i % 2 > 0) {
111 | sumEvenOdd[1] += i;
112 | }
113 | }
114 | console.log(sumEvenOdd)
115 |
116 | //array of five random numbers
117 | let randomArr = [];
118 | for (let i = 0; i < 5; i++) {
119 | randomArr.push(Math.floor(Math.random() * 10));
120 | }
121 | console.log(randomArr)
122 |
123 | //generating random unique arr
124 | let randomUniqueArr = [];
125 | for (let i = 5; randomUniqueArr.length < i;) {
126 | let random = Math.floor(Math.random() * 10);
127 | if (randomUniqueArr.indexOf(random) === -1) {
128 | randomUniqueArr.push(random);
129 | }
130 | }
131 | console.log(randomUniqueArr)
132 |
133 | //generate 6 random numbers/strings
134 | let chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
135 | let randomChars = ""
136 | for (let i = 0; i < 6; i++) {
137 | let random = Math.floor(Math.random() * chars.length);
138 | randomChars += chars[random];
139 | }
140 | console.log(randomChars)
141 |
142 | //generate any number of numbers/strings
143 | let chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
144 | let r = Math.floor(Math.random() * chars.length);
145 | let randChars = "";
146 | for (let i = 0; i < r; i++) {
147 | let random = Math.floor(Math.random() * chars.length);
148 | randChars += chars[random];
149 | }
150 | console.log(randChars);
151 |
152 | let countries = ["ALBANIA", "BOLIVIA", "CANADA", "DENMARK", "ETHIOPIA", "FINLAND", "GERMANY", "HUNGARY", "IRELAND", "JAPAN", "KENYA"];
153 | let newCountries = [];
154 | for (let i = 0; i < countries.length; i++) {
155 | newCountries.push([countries[i], countries[i].slice(0, 3), countries[i].length])
156 | }
157 | console.log(newCountries)
158 | let countWithoutLand = []
159 | let countWithLand = []
160 | for (let i = 0; i < countries.length; i++) {
161 | if (countries[i].includes("LAND")) {
162 | countWithLand.push(countries[i]);
163 | } else {
164 | countWithoutLand.push(countries[i])
165 | }
166 | }
167 |
168 | let countWithIa = []
169 | let countWithoutIa = []
170 | for (let i = 0; i < countries.length; i++) {
171 | if (countries[i].includes("IA")) {
172 | countWithIa.push(countries[i]);
173 | } else {
174 | countWithoutIa.push(countries[i])
175 | }
176 | }
177 |
178 | console.log(`countries with "ia" ${countWithIa}`);
179 | console.log(`countries without "ia" ${countWithoutIa}`)
180 |
181 | let countriesCharLength = [];
182 | for (let i = 0; i < countries.length; i++) {
183 | countriesCharLength.push(countries[i].length);
184 | }
185 | console.log(countriesCharLength);
186 |
187 | let highest;
188 | highestNum = Math.max.apply(null, countriesCharLength);
189 | console.log(countries[countriesCharLength.indexOf(highestNum)]);
190 |
191 | //countries with five chars
192 | let countriesWithFiveChars = [];
193 | for (let i = 0; i < countries.length; i++) {
194 | if (countries[i].length === 5) {
195 | countriesWithFiveChars.push(countries[i])
196 | }
197 | }
198 | console.log(countriesWithFiveChars)
199 |
200 | let webTechs = ["html", "css", "javascript", "vue", "react", "mongodb", "angular"];
201 | let webTechsLength = [];
202 | for (let i = 0; i < webTechs.length; i++) {
203 | webTechsLength.push(webTechs[i].length);
204 | }
205 | console.log(webTechsLength);
206 | let highestChar;
207 | highestChar = Math.max.apply(null, webTechsLength);
208 | console.log(highestChar)
209 | console.log(webTechs[webTechsLength.indexOf(highestChar)]);
210 |
211 | let newWebTechs = [];
212 | for (let i = 0; i < webTechs.length; i++) {
213 | newWebTechs.push([webTechs[i], webTechs[i].length])
214 | }
215 | console.log(newWebTechs)
216 |
217 | let mernStack = ["MongoDb", "Express", "React", "Node"]
218 | let mern = "";
219 | for (let i = 0; i < mernStack.length; i++) {
220 | mern += mernStack[i].slice(0, 0);
221 | }
222 | console.log(mern)
223 |
224 | let techs = ["HTML", "CSS", "JS", "React", "Redux", "Node", "Express", "MongoDB"]
225 | for (let i = 0; i < techs.length; i++) {
226 | console.log(techs[i])
227 | }
228 | for (let tech of techs) {
229 | console.log(tech);
230 | }
231 |
232 | let fruits = ['banana', 'orange', 'mango', 'lemon'];
233 | for (let i = fruits.length - 1; i >= 0; i--) {
234 | console.log(fruits[i]);
235 | }
236 |
237 |
--------------------------------------------------------------------------------
/Day-7/functions.js:
--------------------------------------------------------------------------------
1 | function fullName() {
2 | console.log("victor kenneth")
3 | }
4 | fullName()
5 |
6 | function fullName(firstName, lastName) {
7 | return `${firstName} ${lastName}`;
8 | }
9 | fullName("victor", "kenneth");
10 |
11 | function addNumbers(a, b) {
12 | return a + b;
13 | }
14 | addNumbers(2, 5);
15 |
16 | function areaOfRectangle(length, width) {
17 | let area = length * width;
18 | return area;
19 | }
20 | areaOfRectangle(5, 3);
21 |
22 | perimeterOfRectangle = (length, width) => {
23 | let perimeter = 2 * (length * width);
24 | return perimeter;
25 | }
26 | perimeterOfRectangle(3, 5);
27 |
28 | volumeOfRectPrism = (length, width, height) => {
29 | let volume = length * width * height;
30 | return volume;
31 | }
32 | volumeOfRectPrism(2, 3, 4);
33 |
34 | AreaOfCircle = (r) => {
35 | const PI = 3.14;
36 | let area = PI * r * r;
37 | }
38 | AreaOfCircle(7);
39 |
40 | circumOfCircle = (r) => {
41 | const PI = 3.14;
42 | return PI * r
43 | }
44 | circumOfCircle(6);
45 |
46 | density = (mass, volume) => {
47 | return mass * volume;
48 | }
49 | density(4, 8);
50 |
51 | speed = (TDC, TT) => {
52 | return TDC / TT
53 | }
54 | speed(4, 6);
55 |
56 | weight = (mass, gravity) => {
57 | return mass * gravity;
58 | }
59 | weight(4, 5);
60 |
61 | celsiusToFahrenheit = (celsius) => {
62 | let fahrenheit = (celsius * 9 / 5) + 32
63 | return fahrenheit;
64 | }
65 | celsiusToFahrenheit(5);
66 |
67 | BMI = (weight, height) => {
68 | let bmi = weight / (height / height);
69 | if (bmi < 18.5) {
70 | return `underweight`;
71 | } else if (bmi > 18.5 && bmi < 24.9) {
72 | return `overweight`;
73 | } else if (bmi > 25 && bmi < 29.9) {
74 | return `overweight`;
75 | } else {
76 | return `obese`;
77 | }
78 | }
79 | BMI(4, 7);
80 |
81 | checkSeasons = (month) => {
82 | switch (month) {
83 | case "september":
84 | case "october":
85 | case "November":
86 | console.log("the season is Autumn");
87 | break;
88 | case "december":
89 | case "january":
90 | case "febuary":
91 | console.log("the season is Winter");
92 | break;
93 | case "march":
94 | case "april":
95 | case "may":
96 | console.log("the season is Spring");
97 | break;
98 | case "june":
99 | case "july":
100 | case "august":
101 | console.log("the season is Summer");
102 | break;
103 | default:
104 | console.log("invalid Month")
105 | }
106 | }
107 | checkSeasons("january");
108 |
109 | findMax = (x, y, z) => {
110 | return Math.max(x, y, z);
111 | }
112 | findMax(5, 7, 4)
113 |
114 | printArr = (arr) => {
115 | arr.forEach(function (ar) {
116 | console.log(ar);
117 | })
118 | }
119 | printArr([3, 4, 5])
120 |
121 | showDateTime = () => {
122 | let date = new Date();
123 | let datee = date.getDate();
124 | let month = date.getUTCMonth();
125 | let year = date.getFullYear();
126 | let hour = date.getHours();
127 | let minutes = date.getMinutes();
128 | return `${datee}/${month + 1}/${year} ${hour}:${minutes} `
129 | }
130 | showDateTime();
131 |
132 | swapValues = (a, b) => {
133 | let x = b;
134 | let y = a;
135 | console.log(x, y)
136 | }
137 | swapValues(2, 4)
138 |
139 | reverseArr = (arr) => {
140 | let newArr = [];
141 | for (let i = 0; i < arr.length; i++) {
142 | newArr.unshift(arr[i]);
143 | }
144 | console.log(newArr);
145 | }
146 | reverseArr([3, 4, 5])
147 |
148 | capitalizeArr = (arr) => {
149 | let newArr = [];
150 | arr.forEach(function (ar) {
151 | newArr.push(ar.toUpperCase());
152 | })
153 | return newArr;
154 | }
155 | capitalizeArr(["john", "mike"]);
156 |
157 | removeitem = (index) => {
158 | let names = ["john", "mike"]
159 | names.splice(index);
160 | return names
161 | }
162 | removeitem(1);
163 |
164 | sumOfNumbers = (...args) => {
165 | let sum = 0;
166 | args.forEach(function (arg) {
167 | sum += arg
168 | })
169 | return sum;
170 | }
171 | sumOfNumbers(1, 2, 3, 4)
172 |
173 | sumOfEven = (...args) => {
174 | let evenSum = 0;
175 | args.forEach(function (arg) {
176 | if (arg % 2 === 0) {
177 | evenSum += arg
178 | }
179 | })
180 | return evenSum;
181 | }
182 | sumOfEven(1, 2, 3, 4)
183 |
184 | sumOfOdd = (...args) => {
185 | let oddSum = 0;
186 | args.forEach(function (arg) {
187 | if (arg % 2 === 0) {
188 | oddSum += arg
189 | }
190 | })
191 | return oddSum;
192 | }
193 | sumOfOdd(1, 2, 3, 4)
194 |
195 | evenAndOdds = (num) => {
196 | let odd = 0;
197 | let even = 0;
198 | for (let i = 0; i <= num; i++) {
199 | if (i % 2 === 0) {
200 | even++
201 | } else if (i % 2 !== 0) {
202 | odd++
203 | }
204 | }
205 | return `the number of odds are ${odd} \n the number of even are ${even}`
206 | }
207 | evenAndOdds(100)
208 |
209 | sum = (...args) => {
210 | let sum = 0;
211 | args.forEach(function (num) {
212 | sum += num;
213 | })
214 | }
215 | sum(1, 2, 3)
216 |
217 | generateRandomIp = () => {
218 | let one = Math.floor(Math.random() * 255);
219 | let two = Math.floor(Math.random() * 255);
220 | let three = Math.floor(Math.random() * 255);
221 | let four = Math.floor(Math.random() * 255);
222 | return `IP: ${one}:${two}:${three}:${four}`
223 | }
224 | generateRandomIp();
225 |
226 | generateRandomMacAdd = () => {}
227 |
228 | generateRandomHex = () => {
229 | let chars = "0123456789ABCDEF";
230 | let hex = "";
231 | for (let i = 0; i <= 6; i++) {
232 | hex += chars[Math.floor(Math.random() * chars.length)];
233 | }
234 |
235 | return `#${hex}`
236 | }
237 | generateRandomHex();
238 |
239 | generateUserId = () => {
240 | let chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
241 | let userId = "";
242 | for (let i = 0; i <= 7; i++) {
243 | userId += chars[Math.floor(Math.random() * chars.length)];
244 | }
245 | return userId;
246 | }
247 | generateUserId();
248 |
249 | userIdGeneratedByUser = () => {
250 | let chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
251 | let noId = Number(prompt("how many id do you want to generate"));
252 | let noChars = Number(prompt("in how many chars"));
253 | let ids = [];
254 | for (i = 0; i < noId; i++) {
255 | ids[i] = "";
256 | for (k = 0; k < noChars; k++) {
257 | ids[i] += chars[Math.floor(Math.random() * chars.length)];
258 | }
259 | }
260 | console.log(ids)
261 | ids.forEach(function (id) {
262 | console.log(id);
263 | })
264 | }
265 | userIdGeneratedByUser();
266 |
267 | rgbColorGnerator = () => {
268 | let one = Math.floor(Math.random() * 255);
269 | let two = Math.floor(Math.random() * 255);
270 | let three = Math.floor(Math.random() * 255);
271 | return `rgb(${one},${two},${three})`;
272 | }
273 | rgbColorGnerator();
274 |
275 | arrayOfHexaColors = () => {
276 | let chars = "0123456789ABCDEF";
277 | let hex = [];
278 | for (let k = 0; k < 3; k++) {
279 | hex[k] = "#";
280 | for (let i = 0; i < 6; i++) {
281 | hex[k] += chars[Math.floor(Math.random() * chars.length)];
282 | }
283 | }
284 |
285 | return hex;
286 | }
287 | arrayOfHexaColors();
288 |
289 | generateColors = (type, arrLength) => {
290 | let chars = "0123456789ABCDEF";
291 | let colors = [];
292 | if (type === "rgb") {
293 | for (i = 0; i < arrLength; i++) {
294 | colors[i] = "rgb";
295 | colors[i] += `(${ Math.floor(Math.random() * 255) },`;
296 | colors[i] += `${ Math.floor(Math.random() * 255) },`
297 | colors[i] += `${ Math.floor(Math.random() * 255) },)`
298 | }
299 | } else if (type === "hex") {
300 | for (let i = 0; i < arrLength; i++) {
301 | colors[i] = "#";
302 | for (k = 0; k < 6; k++) {
303 | colors[i] += chars[Math.floor(Math.random() * chars.length)];
304 | }
305 | }
306 | }
307 | return colors;
308 | }
309 | generateColors("rgb", 3);
310 |
311 | shuffleArray = (arr) => {
312 | let newArr = [];
313 | for (let i = 0; i < arr.length; i++) {
314 | let rand = Math.floor(Math.random() * arr.length - 1);
315 | if (arr.indexOf(rand) !== -1 && !newArr.includes(arr[rand])) {
316 | newArr.push(arr[rand]);
317 | }
318 | }
319 | return newArr
320 | }
321 | shuffleArray([1, 2, 3]);
322 |
323 | factorial = (num) => {
324 | let factorial = 1;
325 | for (let i = num; i > 0; i--) {
326 | // if (i === 0) {
327 | // break;
328 | // }
329 |
330 | factorial *= i;
331 | }
332 | return factorial;
333 | }
334 | factorial(5);
335 |
336 | isEmpty = (val) => {
337 | if (val === undefined) {
338 | return `it's empty`
339 | } else {
340 | return `not empty`
341 | }
342 | }
343 | isEmpty()
344 |
345 | sum = (...args) => {
346 | let sum = 0;
347 | args.forEach(function (arg) {
348 | sum += arg
349 | })
350 | return sum;
351 | }
352 | sum(1, 2, 3, 4);
353 |
354 | sumOfArrayItems = (arr) => {
355 | let sum = 0;
356 | arr.forEach(function (ar) {
357 | if (typeof ar === "number") {
358 | sum += ar
359 | } else {
360 | sum = `it's a string`
361 | }
362 | })
363 | return sum;
364 | }
365 | sumOfArrayItems([1, 2, 3])
366 |
367 | average = (arr) => {
368 | let sum = 0;
369 | arr.forEach(function (ar) {
370 | if (typeof ar === "number") {
371 | sum += ar;
372 | sum = arr.length / sum;
373 | } else {
374 | sum = `it's a string`;
375 | }
376 | })
377 | return sum;
378 | }
379 | average([1, 2, 3]);
380 |
381 | modifyArray = (arr) => {
382 | if (arr.length >= 6) {
383 | for (let i = 0; i < arr.length; i++) {
384 | if (i = 5) {
385 | arr.splice(5)
386 | }
387 | }
388 | return arr
389 | } else {
390 | return `item not found`
391 | }
392 | }
393 | modifyArray([1, 2, 3]);
394 |
395 | isPrime = (num) => {
396 | for (let i = 2; i < num; i++) {
397 | if (num % i === 0 && num > 1) {
398 | return `${num} is a prime number`;
399 | } else {
400 | return `not prime`
401 | }
402 | }
403 | }
404 | isPrime(5);
405 |
406 | reverseCountries = () => {
407 | let countries = ["nigeria", "U.S.A", "italy", "canada", "lebanon"];
408 | return countries.reverse();
409 | }
410 | reverseCountries();
--------------------------------------------------------------------------------
/Day-8/level-1.js:
--------------------------------------------------------------------------------
1 | //level-1
2 | let dog = {};
3 | console.log(dog);
4 | dog.name = "jasper";
5 | dog.legs = 4;
6 | dog.color = "brown"
7 | dog.age = 4;
8 | dog.bark = function () {
9 | console.log("woof woof woof")
10 | }
11 | console.log(Object.values(dog));
12 | dog.breed = "german shepherd";
13 | dog.getDogInfo = function () {
14 | console.log(Object.values(this));
15 | }
--------------------------------------------------------------------------------
/Day-8/level-2.js:
--------------------------------------------------------------------------------
1 | // level-2
2 | const users = {
3 | Alex: {
4 | email: 'alex@alex.com',
5 | skills: ['HTML', 'CSS', 'JavaScript'],
6 | age: 20,
7 | isLoggedIn: false,
8 | points: 30
9 | },
10 | Asab: {
11 | email: 'asab@asab.com',
12 | skills: ['HTML', 'CSS', 'JavaScript', 'Redux', 'MongoDB', 'Express', 'React', 'Node'],
13 | age: 25,
14 | isLoggedIn: false,
15 | points: 50
16 | },
17 | Brook: {
18 | email: 'daniel@daniel.com',
19 | skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux'],
20 | age: 30,
21 | isLoggedIn: true,
22 | points: 50
23 | },
24 | Daniel: {
25 | email: 'daniel@alex.com',
26 | skills: ['HTML', 'CSS', 'JavaScript', 'Python'],
27 | age: 20,
28 | isLoggedIn: false,
29 | points: 40
30 | },
31 | John: {
32 | email: 'john@john.com',
33 | skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux', 'Node.js'],
34 | age: 20,
35 | isLoggedIn: true,
36 | points: 50
37 | },
38 | Thomas: {
39 | email: 'thomas@thomas.com',
40 | skills: ['HTML', 'CSS', 'JavaScript', 'React'],
41 | age: 20,
42 | isLoggedIn: false,
43 | points: 40
44 | },
45 | Paul: {
46 | email: 'paul@paul.com',
47 | skills: ['HTML', 'CSS', 'JavaScript', 'MongoDB', 'Express', 'React', 'Node'],
48 | age: 20,
49 | isLoggedIn: false,
50 | points: 40
51 | }
52 | }
53 |
54 | let winner;
55 | let max = 0
56 |
57 | for (const property in users) {
58 | if (users[property].skills.length > max) {
59 | max = users[property].skills.length;
60 | winner = property
61 | }
62 | }
63 | console.log(winner);
64 |
65 | let country = {
66 | name: "Nigeria",
67 | capital: "?",
68 | population: "7 billion",
69 | languages: ["hausa", "igbo", "yoruba"]
70 | }
71 |
72 | console.log(`${country.name}\n${country.capital}\n${country.population}\n${country.languages}`)
--------------------------------------------------------------------------------
/Day-8/level-3.js:
--------------------------------------------------------------------------------
1 | let personAccount = {
2 | firstName: "victor",
3 | lastName: "kenneth",
4 | income: {
5 | freelancing: 10000,
6 | menialLabour: 2000
7 | },
8 | expenses: {
9 | data: 500,
10 | food: 1000,
11 | transport: 500
12 | },
13 |
14 | totalIncome: function () {
15 | let tIncome = 0;
16 | let values = Object.values(this.income);
17 | for (let i = 0; i < values.length; i++) {
18 | tIncome += values[i]
19 | }
20 | return tIncome;
21 | },
22 | totalExpenses: function () {
23 | let tExpenses = 0;
24 | let values = Object.values(this.expenses);
25 | for (let i = 0; i < values.length; i++) {
26 | tExpenses += values[i]
27 | }
28 | return tExpenses
29 | },
30 | accountBalance: function () {
31 | return this.totalIncome() - this.totalExpenses();
32 | },
33 | accountInfo: function () {
34 | return `name:${this.firstName} ${this.lastName}\n
35 | incomes:${Object.entries(this.income)}
36 | expenses: ${
37 | Object.entries(this.expenses)
38 | }
39 | totalIncome: ${this.totalIncome()}
40 | totalExpenses: ${this.totalExpenses()}
41 | accountBalance: ${this.accountBalance()}
42 | `
43 | }
44 | }
45 |
46 | function callBack(add, a, b) {
47 | return add(a, b);
48 | }
49 |
50 | //user
51 | const users = [{
52 | _id: 'ab12ex',
53 | username: 'Alex',
54 | email: 'alex@alex.com',
55 | password: '123123',
56 | createdAt: '08/01/2020 9:00 AM',
57 | isLoggedIn: false
58 | },
59 | {
60 | _id: 'fg12cy',
61 | username: 'Asab',
62 | email: 'asab@asab.com',
63 | password: '123456',
64 | createdAt: '08/01/2020 9:30 AM',
65 | isLoggedIn: true
66 | },
67 | {
68 | _id: 'zwf8md',
69 | username: 'Brook',
70 | email: 'brook@brook.com',
71 | password: '123111',
72 | createdAt: '08/01/2020 9:45 AM',
73 | isLoggedIn: true
74 | },
75 | {
76 | _id: 'eefamr',
77 | username: 'Martha',
78 | email: 'martha@martha.com',
79 | password: '123222',
80 | createdAt: '08/01/2020 9:50 AM',
81 | isLoggedIn: false
82 | },
83 | {
84 | _id: 'ghderc',
85 | username: 'Thomas',
86 | email: 'thomas@thomas.com',
87 | password: '123333',
88 | createdAt: '08/01/2020 10:00 AM',
89 | isLoggedIn: false
90 | }
91 | ];
92 |
93 | const signUp = (username, email, password) => {
94 | users.forEach(user => {
95 | if (user.username === username && user.password === password) {
96 | console.log("you already have an account")
97 | } else {
98 | let date = new Date()
99 | let chars = "abcdefghiklmnopqrstuvwxyz";
100 | let id = [];
101 | for (let i = 0; i < 6; i++) {
102 | id.push(chars[Math.floor(Math.random() * chars.length)])
103 | }
104 | id = id.join("");
105 | users.push({
106 | _id: id,
107 | username: username,
108 | email: email,
109 | password: password,
110 | createdAt: `${date.getDate()}/${date.getMonth()}/${date.getFullYear()} ${date.getHours()}:${date.getMinutes()}`,
111 | isLoggedIn: "false"
112 | })
113 | }
114 | })
115 | console.log(users[users.length - 1]);
116 | }
117 |
118 | const signIn = (username, password) => {
119 | for (let i = 0; i < users.length; i++) {
120 | if (users[i].username.toLowerCase() === username.toLowerCase() && users[0].password === password) {
121 | return users[i];
122 | } else {
123 | return "wrong username or password";
124 | }
125 | }
126 | // console.log(foundUser)
127 | }
128 |
129 | //product
130 | const products = [{
131 | _id: 'eedfcf',
132 | name: 'mobile phone',
133 | description: 'Huawei Honor',
134 | price: 200,
135 | ratings: [{
136 | userId: 'fg12cy',
137 | rate: 5
138 | },
139 | {
140 | userId: 'zwf8md',
141 | rate: 4.5
142 | }
143 | ],
144 | likes: []
145 | },
146 | {
147 | _id: 'aegfal',
148 | name: 'Laptop',
149 | description: 'MacPro: System Darwin',
150 | price: 2500,
151 | ratings: [],
152 | likes: ['fg12cy']
153 | },
154 | {
155 | _id: 'hedfcg',
156 | name: 'TV',
157 | description: 'Smart TV:Procaster',
158 | price: 400,
159 | ratings: [{
160 | userId: 'fg12cy',
161 | rate: 5
162 | }],
163 | likes: ['fg12cy']
164 | }
165 | ]
166 |
167 | const rateProduct = (name, rate) => {
168 | products.forEach(product => {
169 | if (product.name.toLowerCase().includes(name)) {
170 | let chars = "0123456789abcdefghiklmnopqrstuvwxyz";
171 | let id = [];
172 | for (let i = 0; i < 6; i++) {
173 | id.push(chars[Math.floor(Math.random() * chars.length)])
174 | }
175 | id = id.join("");
176 | product.ratings.push({
177 | userId: id,
178 | rate: rate
179 | })
180 | console.log("filter");
181 | } else {
182 | console.log("no product to rate")
183 | }
184 | })
185 | };
186 |
187 | const avgRating = (name) => {
188 | let avg = 0;
189 | let count = 0;
190 | for (let i = 0; i < products.length; i++) {
191 | if (name.toLowerCase() === products[i].name.toLowerCase()) {
192 | products[i].ratings.rate.forEach(rating => {
193 | count++
194 | avg += rating
195 | })
196 | }
197 | }
198 | avg = avg / count
199 | }
200 |
201 | const likeProduct = (name) => {
202 | for (let i = 0; i < products.length; i++) {
203 | if (name.toLowerCase() === products[i].name.toLowerCase()) {
204 |
205 | if (!products[i].likes) {
206 | console.log(like);
207 | let chars = "0123456789abcdefghiklmnopqrstuvwxyz";
208 | let id = [];
209 | for (let i = 0; i < 6; i++) {
210 | id.push(chars[Math.floor(Math.random() * chars.length)])
211 | }
212 | id = id.join("");
213 | products[i].likes.push(id)
214 | } else {
215 | console.log("product has been liked")
216 | }
217 | } else {
218 | console.log("no product available")
219 | }
220 | }
221 | }
222 |
223 | rateProduct("tv", "4.5");
224 | avgRating("mobile phone");
225 | likeProduct("mobile phone");
--------------------------------------------------------------------------------
/Day-9/level-1.js:
--------------------------------------------------------------------------------
1 | //diiference between forEach,map,filter,and reduce
2 | /*
3 | forEach
4 | the forEach method takes in an array
5 | and execute a function for each element in
6 | the array
7 | */
8 |
9 | /*map
10 | the map method produces a new array
11 | from the provided callback function
12 | to be executed on each array
13 | */
14 |
15 | /*filter
16 | this also creates a new array that
17 | passes the test of the callback function provided
18 | */
19 |
20 | /*reduce
21 | this produces a single value from an array
22 | provided it meets the callback function
23 | */
24 |
25 |
26 | const countries = ['Finland', 'Sweden', 'Denmark', 'Norway', 'IceLand']
27 | const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
28 | const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
29 | const products = [{
30 | product: 'banana',
31 | price: 3
32 | },
33 | {
34 | product: 'mango',
35 | price: 6
36 | },
37 | {
38 | product: 'potato',
39 | price: ' '
40 | },
41 | {
42 | product: 'avocado',
43 | price: 8
44 | },
45 | {
46 | product: 'coffee',
47 | price: 10
48 | },
49 | {
50 | product: 'tea',
51 | price: ''
52 | }
53 | ]
54 |
55 | countries.forEach(country => {
56 | console.log(country)
57 | })
58 |
59 | names.forEach(name => {
60 | console.log(name)
61 | })
62 |
63 | numbers.forEach(num => {
64 | console.log(num)
65 | })
66 |
67 | let uppCaseCountries = countries.map(country => {
68 | return country.toUpperCase();
69 | })
70 | console.log(uppCaseCountries);
71 |
72 | let countriesLength = countries.map(country => {
73 | return country.length
74 | })
75 | console.log(countriesLength);
76 |
77 | let squareNum = numbers.map(num => {
78 | return num * num
79 | })
80 | console.log(squareNum);
81 |
82 | let uppCaseNames = names.map(name => {
83 | return name.toUpperCase();
84 | })
85 | console.log(uppCaseNames);
86 |
87 | let prices = products.map(product => {
88 | return `${product.product}:${product.price}`
89 | })
90 | console.log(prices)
91 |
92 | let countriesWithLand = countries.filter(country => {
93 | return country.toLowerCase().includes("land")
94 | })
95 | console.log(countriesWithLand);
96 |
97 | let countriesWith6chars = countries.filter(country => {
98 | return country.length === 6;
99 | })
100 | console.log(countriesWith6chars);
101 |
102 | let countriesWith6charsMore = countries.filter(country => {
103 | return country.length >= 6;
104 | })
105 | console.log(countriesWith6charsMore);
106 |
107 | let countriesStartingWithE = countries.filter(country => {
108 | return country[0].toLowerCase === "e";
109 | })
110 | console.log(countriesStartingWithE);
111 |
112 | let pricesWithValues = products.filter(product => {
113 | return product.price > 0;
114 | })
115 | console.log(pricesWithValues);
116 |
117 | const getStringList = (arr) => {
118 | let nn = arr.filter(item => {
119 | return typeof item === "string"
120 | })
121 | return nn;
122 | }
123 |
124 | let nn = getStringList(["victor", 3, 5, "kenneth"]);
125 | console.log(nn);
126 |
127 | let sumOfNumbers = numbers.reduce((accumulator, currentValue) => {
128 | return accumulator + currentValue;
129 | })
130 | console.log(sumOfNumbers)
131 |
132 | let joinCountries = countries.reduce((accumulator, currentValue) => {
133 | return accumulator + currentValue;
134 | })
135 | console.log(joinCountries);
136 |
137 | //every checks if all elements in an array are similar in all aspects
138 | //some checks if some elements are elements are similar in one aspect
139 |
140 | let isSomelength6 = countries.some(country => {
141 | return country.length > 6;
142 | })
143 | console.log(isSomelength6)
144 |
145 | let isCountryIncludesLand = countries.every(country => {
146 | return country.toLowerCase().includes("land")
147 | })
148 | console.log(isCountryIncludesLand);
149 |
150 | //find returns the first element which satisfies the condition
151 | //findIndex returns the first index elemnt whic satisfiy the condition
152 |
153 | let firstCountry6Chars = countries.find(country => {
154 | return country.length === 6
155 | });
156 | console.log(firstCountry6Chars);
157 |
158 | let firstIndexPosCountry6Chars = countries.findIndex(country => {
159 | return country.length === 6
160 | });
161 | console.log(firstIndexPosCountry6Chars);
162 |
163 | let firstIndexPosNorwayExist = countries.findIndex(country => {
164 | return country.includes("Norway")
165 | });
166 | console.log(firstIndexPosNorwayExist);
167 |
168 | let firstIndexPosRussiaExist = countries.findIndex(country => {
169 | return country.includes("Russia")
170 | });
171 | console.log(firstIndexPosRussiaExist);
--------------------------------------------------------------------------------
/Day-9/level-2.js:
--------------------------------------------------------------------------------
1 | const products = [{
2 | product: 'banana',
3 | price: 3
4 | },
5 | {
6 | product: 'mango',
7 | price: 6
8 | },
9 | {
10 | product: 'potato',
11 | price: ' '
12 | },
13 | {
14 | product: 'avocado',
15 | price: 8
16 | },
17 | {
18 | product: 'coffee',
19 | price: 10
20 | },
21 | {
22 | product: 'tea',
23 | price: ''
24 | }
25 | ]
26 |
27 | const countries = ['Finland', 'Sweden', 'Denmark', 'Norway', 'IceLand', 'italy', 'spain', 'germany', 'portugal', 'england', 'netherland', 'belgium', 'france', 'nigeria', 'U.S.A'];
28 |
29 | let totalPrice = products.map(product => {
30 | return product.price;
31 | }).filter(price => {
32 | return price > 0;
33 | }).reduce((accumulator, currentValue) => {
34 | return accumulator + currentValue;
35 | })
36 | console.log(totalPrice);
37 |
38 | // let sumOfProducts = products.reduce((accumulator, currentValue) => {
39 | // if (products.price > 0) {
40 | // return accumulator + currentValue.price
41 | // }
42 | // })
43 | // console.log(sumOfProducts);
44 |
45 | const categorizeCountries = (countries) => {
46 | let coun = countries.filter(country => {
47 | return country.toLowerCase().includes("ia") || country.toLowerCase().includes("island") || country.toLowerCase().includes("land") || country.toLowerCase().includes("stan");
48 | })
49 | return coun;
50 | }
51 | console.log(categorizeCountries(countries));
52 |
53 | const getFirstTenCountries = (countries) => {
54 | let firstTen = [];
55 | firstTen = countries.map(country => {
56 | return country;
57 | })
58 | return firstTen;
59 | }
60 |
61 | console.log(getFirstTenCountries(countries));
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # 30 Days of JavaScript Solutions
2 | This was a challenge provided by Asabeneh. where he provided tutorials and challenges based on JS
3 |
--------------------------------------------------------------------------------