Skip to content

more solution javascript basic added #85

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions elementaryAlgo/ASCII.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
console.log("a".codePointAt(0));
console.log("a".charCodeAt(0));
console.log(String.fromCharCode(97));
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
let obj = { name: "rabo", age: 44 };
const map = new Map(Object.entries(obj));
console.log(map);
console.log(Object.entries(obj));
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
let obj = { name: "rabo", detail: { age: 70, bank: { byy: 6667, num: 6667 } } };
const allProperties = (obj) => {
for (let prop in obj) {
if (typeof obj[prop] !== "object") {
console.log(prop + " " + obj[prop] + "");
} else {
allProperties(obj[prop]);
}
}
};
console.log(allProperties(obj));
18 changes: 18 additions & 0 deletions elementaryAlgo/JavaScriptCodeChallenge/excludePropUsinJSON.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const obj = {
id: 1,
username: "Rabo",
email: "[email protected]",
password: "password35678",
};
//copy the obj while excluding password
console.log(JSON.stringify(obj, ["id", "username", "email"]));
console.log(JSON.parse(JSON.stringify(obj, ["id", "username", "email"])));

//another way
console.log(
JSON.parse(
JSON.stringify(obj, (key, value) =>
key === "password" ? undefined : value
)
)
);
10 changes: 10 additions & 0 deletions elementaryAlgo/JavaScriptCodeChallenge/firstLastChar.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
function getTheGapX(str) {
if (!str.includes("X")) {
return -1;
}
const firstIndex = str.indexOf("X");
const lastIndex = str.lastIndexOf("X");
return firstIndex === lastIndex ? -1 : lastIndex - firstIndex;
}
console.log(getTheGapX("JavaScript"));
getTheGapX("Xamarin");
7 changes: 7 additions & 0 deletions elementaryAlgo/JavaScriptCodeChallenge/howToEmptyObj.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
let ob = { name: "9" };
for (let key in ob) {
if (ob.hasOwnProperty(key)) {
delete ob[key];
}
}
console.log(ob);
34 changes: 34 additions & 0 deletions elementaryAlgo/JavaScriptCodeChallenge/objectCopy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
const obj = { name: "rabo", description: "black and brain" };
//shallow copy
let shallow = { ...obj };
console.log(shallow);
//shallow copy and add properties
let shallowCopy = { ...obj, age: 0 };
console.log(shallowCopy);
//shallow copy by Object.assign();
let shallowAssign = Object.assign({}, obj, { country: "nigeria" });
console.log(shallowAssign);
//stringify
let dee = { age: 67, email: "[email protected]", desp: { num: 0 } };
let fee = dee;
//console.log(fee.desp === dee.desp);
let copy = JSON.stringify(dee);
console.log(copy);
let copyByJSON = JSON.parse(copy);
//becasue of deep clone these two objects are not the same object
console.log(copyByJSON.desp === dee.desp);
//deep copy: JavaScript do not has a deep copy method but we can implement it
function deepCopy(obj) {
if (!obj) return obj;
let copyObj = {};
for (let key in copyObj) {
if (typeof obj[key] !== "object" || Array.isArray(obj[key])) {
copyObj[key] = obj[key];
} else {
copyObj[key] = deepCopy(obj[key]);
}
}
return copyObj;
}
let t = { name: "rabo", details: { col: "black" } };
console.log(deepCopy(t));
24 changes: 24 additions & 0 deletions elementaryAlgo/JavaScriptCodeChallenge/replaceThreeCenter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
const a = [1, 2, 3, 4, 5];
const b = [4, 0, 0, 0, 8];

const startPositionFor1stArray = a.length / 2 - 1;
const startPositionFor2ndArray = b.length / 2 - 1;
//console.log(startPositionFor1stArray, startPositionFor2ndArray);
console.log(a.splice(startPositionFor1stArray));
a.splice(
startPositionFor1stArray,
3,
...b.slice(startPositionFor2ndArray, startPositionFor2ndArray + 3)
);

const books = [
{ name: "Warcross", author: "Marie Lu" },
{ name: "The Hunger Games", author: "Suzanne Collins" },
{ name: "Harry Potter", author: "Joanne Rowling" },
];
const sortedObj = books.sort((a, b) => {
let book1 = a.author.split(" ")[1];
let book2 = b.author.split(" ")[1];
return book1 < book2 ? 1 : -1;
});
console.log(sortedObj);
6 changes: 6 additions & 0 deletions elementaryAlgo/JavaScriptCodeChallenge/reverseEachWord.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
const str = "JavaScript is awesome";
const arrayReverseWords = str
.split(" ")
.map((word) => word.split("").reverse().join(""))
.join(" ");
console.log(arrayReverseWords);
4 changes: 4 additions & 0 deletions elementaryAlgo/JavaScriptCodeChallenge/reverseNum.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
let num = 3849;

let numStr = String(num);
+numStr.split("").reverse().join(""); // 9483
37 changes: 37 additions & 0 deletions elementaryAlgo/JavaScriptCodeChallenge/threeWaysToLoopStr.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
let str = "hello world";
for (let i = 0; i < str.length; i++) {
console.log(str.charAt(i));
}
for (let word in str) {
console.log(str[word]);
}
[...str].forEach((word) => console.log(word));
for (let char of str) {
console.log(char);
}

Math.abs(-5); // 5
Math.floor(1.6); // 1
Math.ceil(2.4); // 3
Math.round(3.8); // 4
Math.max(-4, 5, 6); // 6
Math.min(-7, -2, 3); // -7
Math.sqrt(64); // 8
Math.pow(5, 3); // 125
Math.trunc(-6.3); // -6
const isInt = (value) => {
return value % 1 === 0;
};
console.log(isInt(1));
console.log(isInt(-6661));
console.log(isInt(0));
console.log(isInt(4.4));
console.log(isInt(1.6));
console.log(1 % 1);
console.log(3 % 1);
console.log(4 % 10);
console.log(50.4 % 1);
const randomNum = (start, end) => {
return Math.floor(Math.random() * (end - start)) + start;
};
console.log(randomNum(1, 5));
111 changes: 111 additions & 0 deletions elementaryAlgo/JavaScriptCodeChallenge/waysToCreateObject.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
let obj = { name: "random", email: "[email protected]" };
const result = Object.create(obj);
result.age = 800;
result.speak = function () {
return `My name is ${this.name} and I am ${this.age} years old.`;
};
console.log(result);
console.log(result.name);
console.log(result.age);
console.log(result.hasOwnProperty("name"));
console.log(result.hasOwnProperty("age"));
console.log(result.hasOwnProperty("speak"));
console.log(result.speak());
let protoRabbit = {
speak(line) {
return `The ${this.type} rabbit says '${line}'`;
},
};
let killerRabbit = Object.create(protoRabbit);
killerRabbit.type = "killer";
console.log(killerRabbit.hasOwnProperty("type"));
console.log(killerRabbit.speak("SKREEEE!"));
// → The killer rabbit says 'SKREEEE!
function factoryFunc(key, value) {
return {
key,
value,
};
}
let factory = new factoryFunc("age", 78);
console.log(factory.value);
console.log(factory.hasOwnProperty("value"));
function facFunc(key, value) {
this[key] = value;
}
const fa = new facFunc("name", 800);
console.log(fa.name);
class Constr {
constructor(name, age = 0) {
this.name = name;
this.age = age;
}
getName() {
return this.name;
}
}
const ob = { name: "hello" };
for (let key in ob) {
if (ob.hasOwnProperty(key)) {
console.log(key);
}
}

for (let key of Object.keys(ob)) {
if (ob.hasOwnProperty(key)) {
console.log(key);
}
}
Object.keys(ob).forEach((key) => {
if (ob.hasOwnProperty(key)) {
console.log(key);
}
});
const countKey = (obj) => {
let count = 0;
Object.keys(obj).forEach((key) => {
if (obj.hasOwnProperty(key)) {
count += 1;
}
});
return count;
};
console.log(countKey(ob));
console.log(Object.create(obj).toString());
console.log(Object.create(null));
let valuePairs = [
["0", 0],
["1", 1],
["2", 2],
];
let objPair = Object.fromEntries(valuePairs);
console.log(objPair);
let map = new Map([
["age", 80],
["name", "rabo"],
]);
let mapPair = Object.fromEntries(map);
console.log(mapPair);
for (let [key, value] of map) {
console.log(key, value);
}
console.log(new Set([8, 9, 0]));
// let obj1 = {age: 56},
// obj2 = {col: 'red'};
// obj1.setPrototypeOf(obj2)
const obj1 = { a: 1 };
const obj2 = { b: 2 };
Object.setPrototypeOf(obj2, obj1);
//obj2.__proto__ = obj1;
console.log(obj1.isPrototypeOf(obj2));
let objWithGetSet = {};
let o = Object.defineProperty(objWithGetSet, "data", {
data: 0,
get() {
return this.value;
},
set(value) {
this.value = value;
},
});
o.data = 90;
4 changes: 4 additions & 0 deletions elementaryAlgo/addTwoNumber.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
const addTwoNumber = (num1, num2) => {
return num1 + num2;
};
console.log(addTwoNumber(2, 4));
17 changes: 17 additions & 0 deletions elementaryAlgo/alvin/alternateCap.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// Write a function `alternatingCaps` that accepts a sentence string as an argument. The function should
// return the sentence where words alternate between lowercase and uppercase.
const alternatingCaps = (words) => {
let result = "";
let arraySplit = words.split(" ");
for (let i = 0; i < arraySplit.length; i++) {
let word = arraySplit[i];
if (i % 2 === 0) {
result += word.toLowerCase() + " ";
} else {
result += word.toUpperCase() + " ";
}
}
return result;
};
console.log(alternatingCaps("take them to school")); // 'take THEM to SCHOOL'
console.log(alternatingCaps("What did ThEy EAT before?")); // 'what DID they EAT before?'
19 changes: 19 additions & 0 deletions elementaryAlgo/alvin/bleepVowels.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// Write a function `bleepVowels` that accepts a string as an argument. The function should return
// a new string where all vowels are replaced with `*`s. Vowels are the letters a, e, i, o, u.
function bleepVowels(str) {
let array = ["a", "e", "i", "o", "u"];
let result = "";
for (let i = 0; i < str.length; i++) {
let char = str[i];
if (array.indexOf(char) > -1) {
result += "*";
} else {
result += char;
}
}
return result;
}
console.log(bleepVowels("skateboard")); // 'sk*t*b**rd'
console.log(bleepVowels("slipper")); // 'sl*pp*r'
console.log(bleepVowels("range")); // 'r*ng*'
console.log(bleepVowels("brisk morning")); // 'br*sk m*rn*ng'
16 changes: 16 additions & 0 deletions elementaryAlgo/alvin/chooseDivisible.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Write a function `chooseDivisibles(numbers, target)` that accepts an array of numbers and a
// target number as arguments. The function should return an array containing elements of the original
// array that are divisible by the target.
const chooseDivisibles = (numbers, target) => {
let result = [];
for (let i = 0; i < numbers.length; i++) {
let num = numbers[i];
if (num % target === 0) {
result.push(num);
}
}
return result;
};
console.log(chooseDivisibles([40, 7, 22, 20, 24], 4)); // [40, 20, 24]
console.log(chooseDivisibles([9, 33, 8, 17], 3)); // [9, 33]
console.log(chooseDivisibles([4, 25, 1000], 10)); // [1000]
16 changes: 16 additions & 0 deletions elementaryAlgo/alvin/combinations.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const combinations = (array) => {
if (array.length === 0) return [[]];
let firstElem = array[0];
let withFirst = array.slice(1);
let combinationWithFirstElem = [];
let combinationWithoutFirstElem = combinations(withFirst);
combinationWithoutFirstElem.forEach((arr) => {
let WithFirstElem = [...arr, firstElem];
combinationWithFirstElem.push(WithFirstElem);
});
return [...combinationWithFirstElem, ...combinationWithoutFirstElem];
};
console.log(combinations(["a", "b", "c"]));
console.log(combinations(["a", "b"]));
//Time : O(2^n)
//Space : O(n * n)
21 changes: 21 additions & 0 deletions elementaryAlgo/alvin/commonElement.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Write a function `commonElements` that accepts two arrays as arguments. The function should return
// a new array containing the elements that are found in both of the input arrays. The order of
// the elements in the output array doesn't matter as long as the function returns the correct elements.
const commonElements = (array1, array2) => {
let result = [];
let set1 = new Set(array1);
let set2 = new Set(array2);
for (let elem of set1) {
if (set2.has(elem)) {
result.push(elem);
}
}
return result;
};
let arr1 = ["a", "c", "d", "b"];
let arr2 = ["b", "a", "y"];
console.log(commonElements(arr1, arr2)); // ['a', 'b']

let arr3 = [4, 7];
let arr4 = [32, 7, 1, 4];
console.log(commonElements(arr3, arr4)); // [4, 7]
15 changes: 15 additions & 0 deletions elementaryAlgo/alvin/divisors.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// Write a function `divisors` that accepts a number as an argument. The function should return an
// array containing all positive numbers that can divide into the argument.
function divisors(num) {
let result = [];
for (let i = 1; i <= num; i++) {
let eachNum = i;
if (num % eachNum === 0) {
result.push(eachNum);
}
}
return result;
}
console.log(divisors(15)); // [1, 3, 5, 15]
console.log(divisors(7)); // [1, 7]
console.log(divisors(24)); // [1, 2, 3, 4, 6, 8, 12, 24]
Loading