![](https://private-user-images.githubusercontent.com/79293287/313464840-1cc7c4f6-0317-4e86-bead-11b50bc8cd97.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3MjUxMDAzMzgsIm5iZiI6MTcyNTEwMDAzOCwicGF0aCI6Ii83OTI5MzI4Ny8zMTM0NjQ4NDAtMWNjN2M0ZjYtMDMxNy00ZTg2LWJlYWQtMTFiNTBiYzhjZDk3LnBuZz9YLUFtei1BbGdvcml0aG09QVdTNC1ITUFDLVNIQTI1NiZYLUFtei1DcmVkZW50aWFsPUFLSUFWQ09EWUxTQTUzUFFLNFpBJTJGMjAyNDA4MzElMkZ1cy1lYXN0LTElMkZzMyUyRmF3czRfcmVxdWVzdCZYLUFtei1EYXRlPTIwMjQwODMxVDEwMjcxOFomWC1BbXotRXhwaXJlcz0zMDAmWC1BbXotU2lnbmF0dXJlPWQ2MTc3MTBhNzRkNzM3MDZhZjgyMDRkODdmMTBhM2VkMjRlZDU0ZDdhMDA2YWYyNTViZDk5NmQ5ZWExMzhmMjYmWC1BbXotU2lnbmVkSGVhZGVycz1ob3N0JmFjdG9yX2lkPTAma2V5X2lkPTAmcmVwb19pZD0wIn0._6z0GtQ1jHL9BGgUTz9wVQ-w9wODw3eEEfZUcpP_X14)
InfiniteJS has been developing in parallel with my web developer career. It was conceived as a more understandable alternative to our dear Eloquent JavaScript, well... for beginners at least. Actually, it turned out to resembled a detective's notebook: practical for inner usage and bit abstract for outer glance. It went beyond JavaScript and covered almost every aspect I encountered in my career growth.
The origin of the tasks is very diverse: I had to thank CS50 for some of them, I encountered some in practice, and some... I tried to offer interesting and wonderful tasks. π΄π» We are starting to enjoy our own little successes! 𧲠π§ β±οΈ
Note
This repo was created in 2024, the tasks provided here are not based on the JavaScript syntax and behavior only, but any other languages can possibly handle them. Since JavaScript is my native programming language and most preferable one and since it as well as my knowledge has been constantly evolving, there are newer language features, newer and better solutions to problems here. Feel free to use them in the tasks! π I would really appreciate a reference to this repo, I gether the tasks and solutions and the community helps me so much to maintain and improve it! πͺπΌ Thank you and have fun! πππ
console.log(sayHello()); // Hello Universe!
function sayHello() {
//Write a function to generate greeting to the whole universe
}
Answer
function sayHello() {
return "Hello Universe!";
}
Do you remember Nintendoβs Super Mario Brothers? Mario must ascend a bunch of right-aligned, left-aligned pyramid of blocks. You must write function, that will receive number from 1 to 9 and build that height pyramids in console, use "#" as building block.
buildRightAligned(5);
// #
// ##
// ###
// ####
// #####
buildLeftAligned(5);
// #
// ##
// ###
// ####
// #####
buildPyramid(5);
// ##
// ####
// ######
// ########
// ##########
Answer
function buildRightAligned(n) {
let node = "";
for (let i = 0; i < n; i++) {
node += "#";
console.log(node);
}
}
function buildLeftAligned(n) {
for (let i = 1; i <= n; i++) {
let node = "";
for (let ii = 1; ii <= n - i; ii++) {
node += " ";
}
for (let ii = 1; ii <= i; ii++) {
node += "#";
}
console.log(node);
}
}
function buildPyramid(n) {
for (let i = 1; i <= n; i++) {
let node = "";
for (let ii = 1; ii <= n - i; ii++) {
node += " ";
}
for (let ii = 1; ii <= i; ii++) {
node += "#";
}
for (let ii = 1; ii <= i; ii++) {
node += "#";
}
console.log(node);
}
}
const arr = [3, "a", "a", "a", 2, 3, "a", 3, "a", 2, 4, 9, 3];
console.log(getMode(arr)); //a - 5 times
function getMode(array) {
//Write a function to find the most frequent item of an array.
}
Answer
function getMode(array) {
let set1 = new Set(array);
let uniqArr = [...set1]; // [3, 'a', 2, 4, 9]
let countArr = [];
for (let i = 0; i < uniqArr.length; i++) {
let counter = 0;
for (let e = 0; e < arr.length; e++) {
if (uniqArr[i] == arr[e]) {
counter++;
}
}
countArr.push(counter); // [4, 5, 2, 1, 1]
}
let maxNum = Math.max(...countArr); //5
let placeNum = countArr.findIndex((e) => e == maxNum); //1
return `${uniqArr[placeNum]} - ${maxNum} times`;
}
let str = "Brown Fox";
console.log(caseToggler(str)); //bROWN fOX
function caseToggler(string) {
//Write a function which accepts string as argument and swaps the case of each character.
}
Answer
function caseToggler(string) {
const array = [...string];
const newArray = Array.from(array, (e) => {
return e == e.toUpperCase() ? e.toLowerCase() : e.toUpperCase();
});
return newArray.join("");
}
const cars = ["Mini", "mini", "fiat", "fiat", "bmw", "mini", "OPEL", "Mini", "opel", "OPEL", "Mini", "bmw", "opel", "OPEL", "bmw", "opel", "bmw", "mini", "opel", "bmw", "fiat", "OPEL", "fiat", "bmw"];
console.log(duplicateRemover(cars));
// 1οΈβ£ ['Mini', 'mini', 'fiat', 'bmw', 'OPEL', 'opel']
// 2οΈβ£ ["mini", "fiat", "bmw", "opel"]
function dublicateRemover(arr) {
//Write a function to remove duplicate items from array (case-sensitive/case-insensitive)
//β - can you think of method-less solution?
}
Answer
function duplicateRemover(arr) {
return arr.filter((e, i) => {
return arr.indexOf(e) === i;
//return arr.indexOf(e.toLowerCase()) === i;
});
}
function duplicateRemover(arr) {
return [...new Set(arr)];
//return [...new Set(arr.map((e) => e.toLowerCase()))];
}
β method-less solution
function duplicateRemover(arr) {
let obj = {};
for (let i = 0; i < arr.length; i++) {
obj[arr[i]] = null;
//obj[arr[i].toLowerCase()] = null;
}
let result = [];
for (let key in obj) {
result.push(key);
}
return result;
}
const nums = [1, 2, -2, 4, 5, 4, 7, 8, 7, 7];
console.log(duplicateFinder(nums)); //["4", "7"];
function duplicateFinder(arr) {
//Write a function to get array of duplicate values in array.
}
Answer
version 1
function cateFinder(arr) {
let result = arr.filter((e, index) => {
return arr.indexOf(e) !== index;
});
return [...new Set(result)];
}
version 2
function duplicateFinder(arr) {
return arr.reduce((acc, cur, i) => {
if (arr.lastIndexOf(cur) !== i && !acc.includes(cur)) {
acc.push(cur);
}
return acc;
}, []);
}
const num1 = [1, 25, 0, 8, 9];
const num2 = [3, 5, 6, 7, 8];
const num3 = [3, 13];
console.log(aggregrate(num1, num2, num3));
//[7, 43, 6, 15, 17]
function aggregrate(...arr) {
//write a function to compute the sum of each individual index value from the given arrays.
}
Answer
function aggregrate(...arr) {
let args = [...arr]; // arguments array
let arrayLengths = args.map((e) => {
return e.length;
}); // array of argument array lengthes
let padLength = Math.max(...arrayLengths);
const AggArray = Array.from({ length: padLength }, (_, i) => {
return 0;
}); // [0, 0, 0, 0, 0]
for (let i = 0; i < padLength; i++) {
args.forEach((e) => {
AggArray[i] += e[i] || 0;
});
}
return AggArray;
}
function aggregrate(...n) {
const array = [];
for (let i = 0; i < n.length; i++) {
for (let y = 0; y < n[i].length; y++) {
array[y] === undefined ? array.push(0) : null;
array[y] += n[i][y];
}
}
return array;
}
const num1 = [1, 2, 3];
const num2 = [6, 2, 1];
const num3 = [8, 2, 1];
const num4 = [3, 5, 1];
console.log(union(num1, num2, num3, num4)); // [1, 2, 3, 6, 8, 5]
function union(...arr) {
//Write a function to compute the union of given arrays with only unique items.
}
Answer
function union(...arr) {
let newSet = new Set([...arr].flat());
return [...newSet];
}
const array = [NaN, 0, 15, false, -22, "", undefined, 47, null, [5, 7]];
console.log(numberify(array)); //[0, 15, -22, 47]
function numberify(arr) {
//Write a function to retrieve only numbers from given array.
}
Answer
function numberify(arr) {
return arr.filter((e) => {
return typeof e === "number" && !isNaN(e);
});
}
const num = [2, 5, 9, 7, 8, 5, 6];
console.log(removeItem(num, 5)); // [2, 9, 7, 8, 6];
function removeItem(array, item) {
//Write a function to remove a specified item from given array.
}
Answer
function removeItem(array, item) {
return array.filter((elem) => elem !== item);
}
console.log(arrayGenerator(6, 5, 2)); //[6, 8, 10, 12, 14]
function arrayGenerator(start, length, step) {
//Write a function to generate array of specified start item, length and increasing by given number
}
Answer
function arrayGenerator(start, length, step) {
let newArr = [start];
for (let i = 0; i < length - 1; i++) {
newArr.push(newArr[i] + step);
}
return newArr;
}
const arr = ["G", "P", "X"];
console.log(fillArr(arr, 5)); //["G", "P", "X", "G", "P"]
function fillArr(arr, n) {
//Write a function which returns array of 'n' length with given array pattern repeating
}
Answer
function fillArr(arr, n) {
let emptyArr = Array.from({ length: n });
return emptyArr.fill(arr).flat().splice(0, n);
}
const genres = [
{
id: 28,
name: "Action",
},
{
id: 12,
name: "Adventure",
},
{
id: 14,
name: "Thriller",
},
{
id: 21,
name: "Drama",
},
];
let ids = [28, 21];
console.log(vlookup(ids, genres)); //['Action', 'Drama']
function vlookup(ids, data) {
//Write a function to generate array of movie ganre names from given ganre id array and ganres data
}
Answer
function vlookup(ids, data) {
let result = [];
ids.forEach((value) => {
data.forEach((e) => {
if (value === e.id) {
result.push(e.name);
}
});
});
return result;
}
const numbers = [23, 42, 14, 57, 67, 69, 78];
console.log(getOddIndex(numbers)); //[0, 3, 4, 5]
function getOddIndex(arr) {
//Write a function to generate array of indexes of odd numbers in given array
}
Answer
function getOddIndex(arr) {
let temp = [];
arr.forEach((e, i) => {
if (e % 2 == 1) {
temp.push(i);
}
});
return temp;
}
let arr1 = [1, 2, 3, 4, 5, 6];
let arr2 = [5, 6, 7, 8, 9];
console.log(overlapExclude(arr1, arr2)); //[1, 2, 3, 4]
function overlapExclude(f, l) {
//Write a function That returns array of numbers from first given array that are not presented in last array
}
Answer
function overlapExclude(f, l) {
return f.filter((num) => {
if (l.indexOf(num) == -1) {
return num;
}
});
}
const members = [
[18, 20], //[age, working experience]
[45, 2],
[61, 12],
[37, 6],
[21, 21],
[78, 9],
];
console.log(openOrSenior(members)); //["Open", "Open", "Senior", "Open", "Open", "Senior"];
function openOrSenior(data) {
// To be a senior, a member must be at least 55 years old and have working experience more than 7 years. Write a function to determine wheather member is Senior or Open
}
Answer
function openOrSenior(data) {
return data.map((e) => {
return e[0] >= 55 && e[1] > 7 ? "Senior" : "Open";
});
}
let deposits = [200, 450, -400, 3000, -650, -130, 70, 1300, 5000, 3400, -150, -790, -3210, -1000, 8500, -30, 200, -200, 340, -300, -20, 50, 400, -460, 430, 1000, 700, 50, 90];
console.log(depositsAbove(1000, deposits)); // 5
function depositsAbove(num, data) {
//Write a function to count deposits above given number for given array of deposits. use reduce() method
}
Answer
function depositsAbove(num, data) {
return data.reduce((count, cur) => (cur > num ? ++count : count), 0);
}
const exceptions = ["a", "an", "and", "the", "but", "or", "on", "in", "with", "of"];
console.log(convertTitleCase("this is a nice title of great writer"));
console.log(convertTitleCase("and then there were NONE"));
// result: "This Is a Nice Title of Great Writer"
// result: "And Then There Were None"
function convertTitleCase(string) {
// Write a function that transfers every word but exceptions to uppercase. Let's assume that given string has no excessive spaces.
// π If you'd like, implement solution that handles excessive spaces
}
Answer
function convertTitleCase(string) {
const capitzalize = (str) => str[0].toUpperCase() + str.slice(1);
const tempString = string
.toLowerCase()
.split(" ")
.map((word) => (exceptions.includes(word) ? word : capitzalize(word)))
.join(" ");
return capitzalize(tempString);
}
const string = " This is a test. ";
console.log(trimmer(string)); //This is a test.
function trimmer(str) {
// Write a function that removes exessive spaces from string
}
Answer
function trimmer(str) {
return str.replace(/ {2,}/g, " ").trim();
}
const whiteSquare = "β";
const BlackSquare = "β";
console.log(chessify(8));
// ββββββββ
// ββββββββ
// ββββββββ
// ββββββββ
// ββββββββ
// ββββββββ
// ββββββββ
// ββββββββ
function chessify(size) {
//Write a function to create chess board in console
}
Answer
function chessify(size) {
let node = "";
for (let horizontalLine = 1; horizontalLine <= size; horizontalLine++) {
let lineNode = "";
for (let verticalLine = 0; verticalLine < size; verticalLine++) {
if (horizontalLine % 2 == 1) {
verticalLine % 2 == 0 ? (lineNode += whiteSquare) : (lineNode += BlackSquare);
} else {
verticalLine % 2 == 0 ? (lineNode += BlackSquare) : (lineNode += whiteSquare);
}
}
node += lineNode + "\n";
}
return node;
}
const users = [
{
id: "64ede4012b31077af2ded83e",
name: "Gould Daniels",
address: "Agate Court, Clarksburg",
balance: "$277.49",
age: 20,
registered: "2017-11-23T10:31:14",
},
{
id: "64ede401d067f20dbc0ea8c3",
name: "Paula Henderson",
address: "Lawton Street, Zarephath",
balance: "$322.43",
age: 12,
registered: "2017-01-13T07:36:37",
},
];
const allowed = ["id", "name", "age"];
console.log(filterIn(users, allowed));
// [
// {
// id: "64ede4012b31077af2ded83e",
// name: "Gould Daniels",
// age: 20,
// },
// {
// id: "64ede401d067f20dbc0ea8c3",
// name: "Paula Henderson",
// age: 12,
// },
// ];
function filterIn(data, arr) {
// Write a function that will remove properties from array of objects, other than specified in given array.
}
Answer
function filterIn(data, arr) {
for (let obj of data) {
Object.keys(obj)
.filter((i) => !arr.includes(i))
.forEach((e) => delete obj[e]);
}
return data;
}
const users = [
{
id: "64ede4012b31077af2ded83e",
name: "Gould Daniels",
address: "Agate Court, Clarksburg",
balance: "$277.49",
age: 20,
registered: "2017-11-23T10:31:14",
},
{
id: "64ede401d067f20dbc0ea8c3",
name: "Paula Henderson",
address: "Lawton Street, Zarephath",
balance: "$322.43",
age: 12,
registered: "2017-01-13T07:36:37",
},
];
const toBeDeleted = ["address", "balance", "registered"];
console.log(filterOut(users, toBeDeleted));
// [
// {
// id: "64ede4012b31077af2ded83e",
// name: "Gould Daniels",
// age: 20,
// },
// {
// id: "64ede401d067f20dbc0ea8c3",
// name: "Paula Henderson",
// age: 12,
// },
// ];
function filterOut(data, arr) {
// Write a function that will remove properties from array of objects specified in given array.
}
Answer
function filterOut(data, arr) {
for (let obj of data) {
arr.forEach((e) => delete obj[e]);
}
return data;
}
const users = [
{
id: "64ede4012b31077af2ded83e",
name: "Gould Daniels",
color: ["#074454", "#364f08", "#ad62a4"],
},
{
id: "64ede401d067f20dbc0ea8c3",
name: "Paula Henderson",
color: ["#490525", "#074454", "#525946"],
},
];
console.log(uniqueColors(users, "color"));
//["#074454", "#364f08", "#ad62a4", "#490525", "#525946"]
function uniqueColors(data, key) {
//Write a function that will collect unique values of given object key
}
Answer
function uniqueColors(data, key) {
return [...new Set(data.map((obj) => obj[key]).flat())];
}
inspired by CS50 π
const DNA = "GGGGAATATGGTTATTAAGTTAAAGAGAAAGAAAGATGTGGGTGATATTAATGAATGAATGAATGAATGAATGAATGAATGTTATGATAGAAGGATAAAAATTAAATAAAATTTTAGTTAATAGAAAAAGAATATATAGAGATCAGATCTATCTATCTATCTTAAGGAGAGGAAGAGATAAAAAAATATAATTAAGGAA";
const STR = "AATG"; //Short Tandem Repeats
console.log(getMaxSequence(DNA, STR)); // 8
// AGATC 2
// AATG 8
// TATC 3
function getMaxSequence(str, subStr) {
// Write a function which returns longest consecutive sequence of substring in string
}
Answer
function getMaxSequence(str, subStr, indexes = [], startIdx = 0) {
const index = str.indexOf(subStr, startIdx);
if (index !== -1) {
indexes.push(index);
getMaxSequence(str, subStr, indexes, index + subStr.length);
}
let counter = 0; // to store longest sequence of repeating STR
let currentCounter = 0; // current sequence of repeating STR
indexes.forEach((e, i) => {
if (indexes[i + 1] - e == subStr.length) {
currentCounter++;
} else {
if (currentCounter > counter) {
counter = currentCounter;
}
currentCounter = 0;
}
});
return counter + 1;
}
const quote = "Education never ends, Watson!";
console.log(getIndexes(quote, "on")); // [7, 26]
function getIndexes(text, str) {
//Write a function to generate array of substring indexes in given quote
}
Answer
function getIndexes(text, str) {
let indexes = [];
let i = -1;
while (text.indexOf(str, i + 1) != -1) {
i = text.indexOf(str, i + 1);
indexes.push(i);
}
return indexes;
}
const flags = ["ARM", "AZR", "GEO", "GEO", "TUR", "GEO"];
console.log(getIndexes(flags, "GEO")); //[2, 3, 5]
function getIndexes(arr, str) {
//Write a function to generate array of indexes of given string in given array. .reduce is preferable
}
Answer
function getIndexes(arr, str) {
return arr.reduce((acc, e, i) => {
if (e == str) {
acc.push(i);
}
return acc;
}, []);
}
const arr1 = [1, 2, 3, 4, 5, 6];
const arr2 = [5, 6, 7, 8, 9];
console.log(findCommonItems(arr1, arr2)); //[5, 6]
function findCommonItems(a, b) {
//Write a function to generate array of items common for pair of given arrays
}
Answer
function findCommonItems(a, b) {
return a.filter((num) => {
if (b.includes(num)) {
return num;
}
});
}
const array = [
[1, 2, 3, 4],
[3, 4, 5, 6],
[2, 3, 4, 7],
];
console.log(bulkOverlaping(array)); // [3, 4]
function bulkOverlaping(arr) {
//Write a function to generate array of items common for arrays inside given array
}
Answer
function bulkOverlaping(arr) {
const commonNumbers = [];
for (let i = 0; i < arr[0].length; i++) {
if (arr.every((array) => array.includes(arr[0][i]))) {
commonNumbers.push(arr[0][i]);
}
}
return commonNumbers;
}
function bulkOverlaping(arr) {
let commonNumbers = arr.reduce((acc, e) => {
e.forEach((item) => {
if (arr.every((array) => array.includes(item))) {
acc.push(item);
}
});
return acc;
}, []);
return [...new Set(commonNumbers)];
}
An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
const word1 = "listen";
const word2 = "silent";
console.log(areAnagrams(word1, word2)); // true
function areAnagrams(word1, word2) {
//Write a function to find if given words are anagrams.
}
Answer
function areAnagrams(word1, word2) {
const sortedWord1 = [...word1.toLowerCase()].sort().join("");
const sortedWord2 = [...word2.toLowerCase()].sort().join("");
return sortedWord1 === sortedWord2;
}
const array = [-5, -4, -3, 0, 2, 5, 8, 9];
console.log(hasZeroSumPair(array));
function hasZeroSumPair(arr) {
//Write a function that will return boolean "TRUE", if it finds 2 numbers in given array, which sums up to zero
//consider: -0 === 0 is true in JS
}
Answer
function hasZeroSumPair(arr) {
for (let num of arr) {
if (num === 0 && num === -0) continue;
// as (-0 === 0) is true in JS, we must skip 0 in iteration
if (arr.includes(-num)) {
return true;
}
}
return false;
}
const keys = ["name", "age", "country"];
const values = ["Tom", 29, "Poland"];
console.log(objectify(keys, values));
// {name: 'Tom', age: 29, country: 'Poland'}
function objectify(arr1, arr2) {
//Write a function that creates object with key names for given 1st array and values from given 2nd array
}
Answer
1. Nice-n-easy solutionfunction objectify(arr1, arr2) {
let obj = {};
arr1.forEach((e, i) => {
obj[e] = arr2[i];
});
return obj;
}
- More advanced technics
function objectify(arr1, arr2) {
return Object.fromEntries(
arr1.reduce((acc, __, i) => {
acc.push([arr1[i], arr2[i]]);
return acc;
}, [])
);
}
let array1 = [1, 5, 3, 2];
let array2 = [5, 2, 3, 1];
console.log(isEqual(array1, array2));
function isEqual(arr1, arr2) {
//write a function, that checks if 2 number arrays are equal
}
Answer
more ad hoc or improvised approachfunction isEqual(arr1, arr2) {
//avoid loop execution when empty and not equly-sized arrays
if (arr1.length != arr2.length) return false;
if (!arr1.length) return true;
let status = true;
let temp1 = [...arr1];
let temp2 = [...arr2];
const LENGTH = temp1.length;
temp1.sort(function (a, b) {
return b - a;
});
temp2.sort(function (a, b) {
return b - a;
});
for (let i = 0; i < LENGTH; i++) {
if (temp1[i] == temp2[i]) continue;
status = false;
}
return status;
}
pattern approach
function isEqual(arr1, arr2) {
//avoid execution when not equly-sized arrays
if (arr1.length != arr2.length) return false;
const frequencies = {};
for (let i = 0; i < arr1.length; i++) {
let element1 = arr1[i];
let element2 = arr2[i];
frequencies[element1] = (frequencies[element1] || 0) + 1;
frequencies[element2] = (frequencies[element2] || 0) - 1;
}
for (let key in frequencies) {
if (frequencies[key] !== 0) return false;
}
return true;
}
const inbox = [
{ from: "alice@beer.com", to: "bob@code.com", subject: "Urgent Meeting Required", body: "We need to discuss the project milestones." },
{ from: "carol@tech.com", to: "dan@developer.com", subject: "System Update Report", body: "Please fix this critical bug ASAP." },
{ from: "eve@company.com", to: "frank@client.com", subject: "Project Deadline Approaching", body: "Please review the project timeline." },
{ from: "grace@management.com", to: "beer@project.com", subject: "Quick Sync", body: "We are out of supplies, please restock!" },
{ from: "ivan@development.com", to: "judy@bugs.com", subject: "Code Review", body: "Letβs ensure our code is clean and maintainable." },
{ from: "kyle@support.com", to: "laura@customer.com", subject: "Update on Support Ticket", body: "Your issue will be resolved before the bedtime." },
];
const spam = ["beer", "bug", "deadline"];
console.log(spamDetector(spam, inbox));
//all objects get 'spam: true' but LAST ONE, as none on the words are found in last object
function spamDetector(words, objects) {
// Write a function with 2 arguments (array of words and array of objects) that will check every object properties against given words (case insensitive) and if found, will add "spam:true" property to that object
//TIP: This is all about loops, as we have 3 words, 6 objects and 4 properties in each, total of 72 iterations will occur. Try to avoid excessive ones by 2 way optimization: 1) when iterating object properties, with early match, there is no need to go through all properties 2) as object already has 'spam: true' property, we can skip it.
}
Answer
function spamDetector(words, objects) {
let status = true;
for (const word of words) {
for (const object of objects) {
if (object.spam == undefined) {
for (const key in object) {
status = String(object[key]).toLowerCase().includes(word);
if (status) break;
}
if (status) {
object.spam = status;
}
}
}
}
return objects;
}
const arr = ["A", "C", "B"];
console.log(reverseArray(arr));
// β ["B", "C", "A"];
function reverseArray(arr) {
// Write a function which will reverse sequence of array items. reverse() is too simple, isn't it?
}
Answer
function reverseArray(arr) {
let newArr = [];
for (let i = arr.length - 1; i >= 0; i--) {
newArr.push(arr[i]);
}
return newArr;
}
super short version
function reverseArray(arr) {
return arr.map((_, i, arr) => arr[arr.length - i - 1]);
}
const string = "i'm gonna win";
console.log(stringReverse(string)); //niw annog m'i
function stringReverse(str) {
// Write a function which will reverse given string
}
Answer
function stringReverse(str) {
return str
.split("")
.map((_, i, r) => r[r.length - i - 1]) // .reverse()
.join("");
}
function isPalindrome(word) {
// Write a function which will check if given word is a palindrome
}
console.log(isPalindrome("rotator")); // true
console.log(isPalindrome("hello")); // false
Answer
function isPalindrome(word) {
return word === word.split("").reverse().join("");
}
const array = [1, 3, 7, 5, 6, 4, 9, 1];
const num = 4;
console.log(maxSubarraySum(array, num)); // 24
function stringReverse(str) {
// Write a function which will calculate from given array and integer maximum given-number-sized-subarray sum
//[1, 3, 7, 5] - 16 β
//[3, 7, 5, 6] - 21 β
//[7, 5, 6, 4] - 22 β
//[5, 6, 4, 9] - 24 βοΈ
//[6, 4, 9, 1] - 20 β
// π‘: "sliding window" algorithm is best solution here, try to guess most ergonomic and mathematical solution or at least solve it
}
Answer
version 1 (very casual)
function maxSubarraySum(arr, size) {
if (size > arr.length) {
return null;
}
const subArraysCount = arr.length - size + 1;
//count number of arrays of {size} neighbouring numbers
const arrayOfArrays = [];
for (let i = 0; i < subArraysCount; i++) {
let tempArrayOfSize = [];
for (let ii = i; ii < size + i; ii++) {
tempArrayOfSize.push(arr[ii]);
}
arrayOfArrays.push(tempArrayOfSize);
}
//nested loop to generate array of arrays of {size} neighbouring numbers
//[[1, 3, 7, 5], [3, 7, 5, 6],....]
const ArrayOfSums = arrayOfArrays.map((e) => {
return e.reduce((acc, cur) => {
return acc + cur;
}, 0);
});
//array of summed sub arrays
return Math.max(...ArrayOfSums);
}
version 2 ("Sliding Window" pattern)
function maxSubarraySum(arr, size) {
if (size > arr.length) {
return null;
}
let maxSum = 0;
let tempSum = 0;
// initialize the window
for (let i = 0; i < num; i++) {
maxSum += arr[i];
}
tempSum = maxSum;
// slide the window over the array
for (let i = num; i < arr.length; i++) {
tempSum = tempSum - arr[i - num] + arr[i];
maxSum = Math.max(maxSum, tempSum);
}
return maxSum;
}
const string = "innovation";
console.log(countVowelsAndConsonants(string)); //{vowels: 5, consonants: 5}
function countVowelsAndConsonants(word) {
// Write a function which will count vowels and consonants in the given word
}
Answer
function countVowelsAndConsonants(word) {
const vowelsArr = ["i", "e", "o", "u", "a"];
let arr = word.toLowerCase().split("");
let vowels = 0;
let consonants = 0;
for (let i = 0; i < arr.length; i++) {
if (vowelsArr.includes(arr[i])) {
vowels++;
} else {
consonants++;
}
}
return { vowels, consonants };
}
const arrayOfObjects = [
{ name: "Ann", age: 25, city: "Paris" },
{ name: "Thomas", age: 30, country: "USA" },
{ name: "Salomea", city: "Tbilisi", occupation: "Engineer" },
];
console.log(uniqueKeys(arrayOfObjects));
// ['name', 'age', 'city', 'country', 'occupation']
function uniqueKeys(arr) {
// Write a function to generate array of unique keys from given array of objects
}
Answer
function uniqueKeys(arr) {
const allKeys = arr.flatMap((e) => Object.keys(e));
return [...new Set(allKeys)];
}
const string1 = "The quick brown fox jumps over the lazy dog";
const string2 = "Waltz, bad nymph, for quick jigs vex.";
const string3 = "The five boxing wizard jump quickly.";
console.log(isPangram(string1)); // βοΈ true
console.log(isPangram(string2)); // βοΈ true
console.log(isPangram(string3)); // β false (missing 's')
function isPangram(sentence) {
// Write a function to checks if given string is pangram
//π‘ A pangram or holoalphabetic sentence is a sentence using every letter of a given alphabet at least once.
}
Answer
function isPangram(sentence) {
let arr = [
...new Set(
sentence
.toLowerCase()
.replace(/[^a-z]/g, "") // removes non-letter characters
.split("")
),
];
return arr.length == 26;
}
function isPangram(sentence) {
sentence = sentence.toLowerCase();
const alphabetSet = new Set();
for (const char of sentence) {
if (/[a-z]/.test(char)) {
alphabetSet.add(char);
}
}
return alphabetSet.size === 26;
}
console.log(countUniqueLetters("Mississippi")); // { m: 1, i: 4, s: 4, p: 2 }
function countUniqueLetters(str) {
//Write a function that coutns unique letters in string
}
Answer
function countUniqueLetters(str) {
str = str.toLowerCase();
const letterCounts = {};
// Iterate through each character in the word
for (const char of str) {
// Check if the character is a letter (a-z)
if (/[a-z]/.test(char)) {
// If the letter exists in the object, increment its count
if (letterCounts[char]) {
letterCounts[char]++;
} else {
// If the letter is new, initialize its count to 1
letterCounts[char] = 1;
}
}
}
return letterCounts;
}
const couples = [10, 5, 10, 7, 5, 12, 13];
console.log(findUniqueNumbers(couples)); // [7, 12, 13]
function findUniqueNumbers(arr) {
//Write a function that creates array on unique number in given array
}
Answer
function findUniqueNumbers(arr) {
return arr.reduce((acc, cur) => {
if (arr.lastIndexOf(cur) == arr.indexOf(cur)) {
acc.push(cur);
}
return acc;
}, []);
}
function findUniqueNumbers(arr) {
const numberCounts = {};
// Iterate through the array and count occurrences
for (const num of arr) {
if (numberCounts[num]) {
numberCounts[num]++;
} else {
numberCounts[num] = 1;
}
}
return arr.filter((num) => numberCounts[num] === 1);
}
const numbers = [2, 8, [6, 3, 3], [4], 5, [3, 4, [5, 4]]];
console.log(arrayCounter(numbers)); // 3
function arrayCounter(arr) {
//Write a function to count number of first-level nested arrays
}
Answer
function arrayCounter(arr) {
return arr.filter((n) => Array.isArray(n)).length;
}
const myArray = [1, 3, 2, 2, 3, 2];
console.log(removeElement(myArray, 2)); //3
function removeElement(arr, val) {
// Write a function to remove given element (val) from array and then return array length
}
Answer
function removeElement(arr, val) {
let k = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i] !== val) {
k++;
}
}
return k;
}