Skip to content

Commit 65d3463

Browse files
committed
more solution javascript basic added
1 parent 675f694 commit 65d3463

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

86 files changed

+2670
-0
lines changed

elementaryAlgo/ASCII.js

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
console.log("a".codePointAt(0));
2+
console.log("a".charCodeAt(0));
3+
console.log(String.fromCharCode(97));
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
let obj = { name: "rabo", age: 44 };
2+
const map = new Map(Object.entries(obj));
3+
console.log(map);
4+
console.log(Object.entries(obj));
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
let obj = { name: "rabo", detail: { age: 70, bank: { byy: 6667, num: 6667 } } };
2+
const allProperties = (obj) => {
3+
for (let prop in obj) {
4+
if (typeof obj[prop] !== "object") {
5+
console.log(prop + " " + obj[prop] + "");
6+
} else {
7+
allProperties(obj[prop]);
8+
}
9+
}
10+
};
11+
console.log(allProperties(obj));
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
const obj = {
2+
id: 1,
3+
username: "Rabo",
4+
5+
password: "password35678",
6+
};
7+
//copy the obj while excluding password
8+
console.log(JSON.stringify(obj, ["id", "username", "email"]));
9+
console.log(JSON.parse(JSON.stringify(obj, ["id", "username", "email"])));
10+
11+
//another way
12+
console.log(
13+
JSON.parse(
14+
JSON.stringify(obj, (key, value) =>
15+
key === "password" ? undefined : value
16+
)
17+
)
18+
);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
function getTheGapX(str) {
2+
if (!str.includes("X")) {
3+
return -1;
4+
}
5+
const firstIndex = str.indexOf("X");
6+
const lastIndex = str.lastIndexOf("X");
7+
return firstIndex === lastIndex ? -1 : lastIndex - firstIndex;
8+
}
9+
console.log(getTheGapX("JavaScript"));
10+
getTheGapX("Xamarin");
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
let ob = { name: "9" };
2+
for (let key in ob) {
3+
if (ob.hasOwnProperty(key)) {
4+
delete ob[key];
5+
}
6+
}
7+
console.log(ob);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
const obj = { name: "rabo", description: "black and brain" };
2+
//shallow copy
3+
let shallow = { ...obj };
4+
console.log(shallow);
5+
//shallow copy and add properties
6+
let shallowCopy = { ...obj, age: 0 };
7+
console.log(shallowCopy);
8+
//shallow copy by Object.assign();
9+
let shallowAssign = Object.assign({}, obj, { country: "nigeria" });
10+
console.log(shallowAssign);
11+
//stringify
12+
let dee = { age: 67, email: "[email protected]", desp: { num: 0 } };
13+
let fee = dee;
14+
//console.log(fee.desp === dee.desp);
15+
let copy = JSON.stringify(dee);
16+
console.log(copy);
17+
let copyByJSON = JSON.parse(copy);
18+
//becasue of deep clone these two objects are not the same object
19+
console.log(copyByJSON.desp === dee.desp);
20+
//deep copy: JavaScript do not has a deep copy method but we can implement it
21+
function deepCopy(obj) {
22+
if (!obj) return obj;
23+
let copyObj = {};
24+
for (let key in copyObj) {
25+
if (typeof obj[key] !== "object" || Array.isArray(obj[key])) {
26+
copyObj[key] = obj[key];
27+
} else {
28+
copyObj[key] = deepCopy(obj[key]);
29+
}
30+
}
31+
return copyObj;
32+
}
33+
let t = { name: "rabo", details: { col: "black" } };
34+
console.log(deepCopy(t));
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
const a = [1, 2, 3, 4, 5];
2+
const b = [4, 0, 0, 0, 8];
3+
4+
const startPositionFor1stArray = a.length / 2 - 1;
5+
const startPositionFor2ndArray = b.length / 2 - 1;
6+
//console.log(startPositionFor1stArray, startPositionFor2ndArray);
7+
console.log(a.splice(startPositionFor1stArray));
8+
a.splice(
9+
startPositionFor1stArray,
10+
3,
11+
...b.slice(startPositionFor2ndArray, startPositionFor2ndArray + 3)
12+
);
13+
14+
const books = [
15+
{ name: "Warcross", author: "Marie Lu" },
16+
{ name: "The Hunger Games", author: "Suzanne Collins" },
17+
{ name: "Harry Potter", author: "Joanne Rowling" },
18+
];
19+
const sortedObj = books.sort((a, b) => {
20+
let book1 = a.author.split(" ")[1];
21+
let book2 = b.author.split(" ")[1];
22+
return book1 < book2 ? 1 : -1;
23+
});
24+
console.log(sortedObj);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
const str = "JavaScript is awesome";
2+
const arrayReverseWords = str
3+
.split(" ")
4+
.map((word) => word.split("").reverse().join(""))
5+
.join(" ");
6+
console.log(arrayReverseWords);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
let num = 3849;
2+
3+
let numStr = String(num);
4+
+numStr.split("").reverse().join(""); // 9483
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
let str = "hello world";
2+
for (let i = 0; i < str.length; i++) {
3+
console.log(str.charAt(i));
4+
}
5+
for (let word in str) {
6+
console.log(str[word]);
7+
}
8+
[...str].forEach((word) => console.log(word));
9+
for (let char of str) {
10+
console.log(char);
11+
}
12+
13+
Math.abs(-5); // 5
14+
Math.floor(1.6); // 1
15+
Math.ceil(2.4); // 3
16+
Math.round(3.8); // 4
17+
Math.max(-4, 5, 6); // 6
18+
Math.min(-7, -2, 3); // -7
19+
Math.sqrt(64); // 8
20+
Math.pow(5, 3); // 125
21+
Math.trunc(-6.3); // -6
22+
const isInt = (value) => {
23+
return value % 1 === 0;
24+
};
25+
console.log(isInt(1));
26+
console.log(isInt(-6661));
27+
console.log(isInt(0));
28+
console.log(isInt(4.4));
29+
console.log(isInt(1.6));
30+
console.log(1 % 1);
31+
console.log(3 % 1);
32+
console.log(4 % 10);
33+
console.log(50.4 % 1);
34+
const randomNum = (start, end) => {
35+
return Math.floor(Math.random() * (end - start)) + start;
36+
};
37+
console.log(randomNum(1, 5));
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
let obj = { name: "random", email: "[email protected]" };
2+
const result = Object.create(obj);
3+
result.age = 800;
4+
result.speak = function () {
5+
return `My name is ${this.name} and I am ${this.age} years old.`;
6+
};
7+
console.log(result);
8+
console.log(result.name);
9+
console.log(result.age);
10+
console.log(result.hasOwnProperty("name"));
11+
console.log(result.hasOwnProperty("age"));
12+
console.log(result.hasOwnProperty("speak"));
13+
console.log(result.speak());
14+
let protoRabbit = {
15+
speak(line) {
16+
return `The ${this.type} rabbit says '${line}'`;
17+
},
18+
};
19+
let killerRabbit = Object.create(protoRabbit);
20+
killerRabbit.type = "killer";
21+
console.log(killerRabbit.hasOwnProperty("type"));
22+
console.log(killerRabbit.speak("SKREEEE!"));
23+
// → The killer rabbit says 'SKREEEE!
24+
function factoryFunc(key, value) {
25+
return {
26+
key,
27+
value,
28+
};
29+
}
30+
let factory = new factoryFunc("age", 78);
31+
console.log(factory.value);
32+
console.log(factory.hasOwnProperty("value"));
33+
function facFunc(key, value) {
34+
this[key] = value;
35+
}
36+
const fa = new facFunc("name", 800);
37+
console.log(fa.name);
38+
class Constr {
39+
constructor(name, age = 0) {
40+
this.name = name;
41+
this.age = age;
42+
}
43+
getName() {
44+
return this.name;
45+
}
46+
}
47+
const ob = { name: "hello" };
48+
for (let key in ob) {
49+
if (ob.hasOwnProperty(key)) {
50+
console.log(key);
51+
}
52+
}
53+
54+
for (let key of Object.keys(ob)) {
55+
if (ob.hasOwnProperty(key)) {
56+
console.log(key);
57+
}
58+
}
59+
Object.keys(ob).forEach((key) => {
60+
if (ob.hasOwnProperty(key)) {
61+
console.log(key);
62+
}
63+
});
64+
const countKey = (obj) => {
65+
let count = 0;
66+
Object.keys(obj).forEach((key) => {
67+
if (obj.hasOwnProperty(key)) {
68+
count += 1;
69+
}
70+
});
71+
return count;
72+
};
73+
console.log(countKey(ob));
74+
console.log(Object.create(obj).toString());
75+
console.log(Object.create(null));
76+
let valuePairs = [
77+
["0", 0],
78+
["1", 1],
79+
["2", 2],
80+
];
81+
let objPair = Object.fromEntries(valuePairs);
82+
console.log(objPair);
83+
let map = new Map([
84+
["age", 80],
85+
["name", "rabo"],
86+
]);
87+
let mapPair = Object.fromEntries(map);
88+
console.log(mapPair);
89+
for (let [key, value] of map) {
90+
console.log(key, value);
91+
}
92+
console.log(new Set([8, 9, 0]));
93+
// let obj1 = {age: 56},
94+
// obj2 = {col: 'red'};
95+
// obj1.setPrototypeOf(obj2)
96+
const obj1 = { a: 1 };
97+
const obj2 = { b: 2 };
98+
Object.setPrototypeOf(obj2, obj1);
99+
//obj2.__proto__ = obj1;
100+
console.log(obj1.isPrototypeOf(obj2));
101+
let objWithGetSet = {};
102+
let o = Object.defineProperty(objWithGetSet, "data", {
103+
data: 0,
104+
get() {
105+
return this.value;
106+
},
107+
set(value) {
108+
this.value = value;
109+
},
110+
});
111+
o.data = 90;

elementaryAlgo/addTwoNumber.js

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
const addTwoNumber = (num1, num2) => {
2+
return num1 + num2;
3+
};
4+
console.log(addTwoNumber(2, 4));

elementaryAlgo/alvin/alternateCap.js

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
// Write a function `alternatingCaps` that accepts a sentence string as an argument. The function should
2+
// return the sentence where words alternate between lowercase and uppercase.
3+
const alternatingCaps = (words) => {
4+
let result = "";
5+
let arraySplit = words.split(" ");
6+
for (let i = 0; i < arraySplit.length; i++) {
7+
let word = arraySplit[i];
8+
if (i % 2 === 0) {
9+
result += word.toLowerCase() + " ";
10+
} else {
11+
result += word.toUpperCase() + " ";
12+
}
13+
}
14+
return result;
15+
};
16+
console.log(alternatingCaps("take them to school")); // 'take THEM to SCHOOL'
17+
console.log(alternatingCaps("What did ThEy EAT before?")); // 'what DID they EAT before?'

elementaryAlgo/alvin/bleepVowels.js

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// Write a function `bleepVowels` that accepts a string as an argument. The function should return
2+
// a new string where all vowels are replaced with `*`s. Vowels are the letters a, e, i, o, u.
3+
function bleepVowels(str) {
4+
let array = ["a", "e", "i", "o", "u"];
5+
let result = "";
6+
for (let i = 0; i < str.length; i++) {
7+
let char = str[i];
8+
if (array.indexOf(char) > -1) {
9+
result += "*";
10+
} else {
11+
result += char;
12+
}
13+
}
14+
return result;
15+
}
16+
console.log(bleepVowels("skateboard")); // 'sk*t*b**rd'
17+
console.log(bleepVowels("slipper")); // 'sl*pp*r'
18+
console.log(bleepVowels("range")); // 'r*ng*'
19+
console.log(bleepVowels("brisk morning")); // 'br*sk m*rn*ng'
+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
// Write a function `chooseDivisibles(numbers, target)` that accepts an array of numbers and a
2+
// target number as arguments. The function should return an array containing elements of the original
3+
// array that are divisible by the target.
4+
const chooseDivisibles = (numbers, target) => {
5+
let result = [];
6+
for (let i = 0; i < numbers.length; i++) {
7+
let num = numbers[i];
8+
if (num % target === 0) {
9+
result.push(num);
10+
}
11+
}
12+
return result;
13+
};
14+
console.log(chooseDivisibles([40, 7, 22, 20, 24], 4)); // [40, 20, 24]
15+
console.log(chooseDivisibles([9, 33, 8, 17], 3)); // [9, 33]
16+
console.log(chooseDivisibles([4, 25, 1000], 10)); // [1000]

elementaryAlgo/alvin/combinations.js

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
const combinations = (array) => {
2+
if (array.length === 0) return [[]];
3+
let firstElem = array[0];
4+
let withFirst = array.slice(1);
5+
let combinationWithFirstElem = [];
6+
let combinationWithoutFirstElem = combinations(withFirst);
7+
combinationWithoutFirstElem.forEach((arr) => {
8+
let WithFirstElem = [...arr, firstElem];
9+
combinationWithFirstElem.push(WithFirstElem);
10+
});
11+
return [...combinationWithFirstElem, ...combinationWithoutFirstElem];
12+
};
13+
console.log(combinations(["a", "b", "c"]));
14+
console.log(combinations(["a", "b"]));
15+
//Time : O(2^n)
16+
//Space : O(n * n)

elementaryAlgo/alvin/commonElement.js

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// Write a function `commonElements` that accepts two arrays as arguments. The function should return
2+
// a new array containing the elements that are found in both of the input arrays. The order of
3+
// the elements in the output array doesn't matter as long as the function returns the correct elements.
4+
const commonElements = (array1, array2) => {
5+
let result = [];
6+
let set1 = new Set(array1);
7+
let set2 = new Set(array2);
8+
for (let elem of set1) {
9+
if (set2.has(elem)) {
10+
result.push(elem);
11+
}
12+
}
13+
return result;
14+
};
15+
let arr1 = ["a", "c", "d", "b"];
16+
let arr2 = ["b", "a", "y"];
17+
console.log(commonElements(arr1, arr2)); // ['a', 'b']
18+
19+
let arr3 = [4, 7];
20+
let arr4 = [32, 7, 1, 4];
21+
console.log(commonElements(arr3, arr4)); // [4, 7]

elementaryAlgo/alvin/divisors.js

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// Write a function `divisors` that accepts a number as an argument. The function should return an
2+
// array containing all positive numbers that can divide into the argument.
3+
function divisors(num) {
4+
let result = [];
5+
for (let i = 1; i <= num; i++) {
6+
let eachNum = i;
7+
if (num % eachNum === 0) {
8+
result.push(eachNum);
9+
}
10+
}
11+
return result;
12+
}
13+
console.log(divisors(15)); // [1, 3, 5, 15]
14+
console.log(divisors(7)); // [1, 7]
15+
console.log(divisors(24)); // [1, 2, 3, 4, 6, 8, 12, 24]

0 commit comments

Comments
 (0)