Skip to content

πŸ”° InfiniteJS Tasks - Basic building 🧱 you must taste! πŸ”₯πŸ’

Notifications You must be signed in to change notification settings

tsotneforester/InfiniteJSTasks

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

55 Commits
Β 
Β 

Repository files navigation

πŸ”°οΈ±π—ΆΜ…Μ²π—»Μ…Μ²π—³Μ…Μ²π—ΆΜ…Μ²π—»Μ…Μ²π—ΆΜ…Μ²π˜Μ…Μ²π—²Μ…Μ²π—Μ…Μ²π—¦Μ…Μ²οΈ±πŸ”° πŸš¦οΈ±πŸ†ƒπŸ…°πŸ†‚πŸ…ΊπŸ†‚

Typing SVG

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! πŸŽ‰πŸŽ‰πŸŽ‰

Please join my discord channel

Discord


🟒 01 - Hello Universe!

console.log(sayHello()); // Hello Universe!

function sayHello() {
  //Write a function to generate greeting to the whole universe
}
Answer
function sayHello() {
  return "Hello Universe!";
}

🟒 02 - Super Mario

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);
  }
}

🟒 03 - Mode

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`;
}

🟒 04 - Toggle Case

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("");
}

🟒 05 - iDuplicate

const cars = ["bmw", "opel", "lada", "opel", "BMW"];
console.log(dublicateRemover(cars)); // ['bmw', 'opel', 'lada']

function dublicateRemover(array) {
  //Write a function to remove duplicate items from array (case insensitivity) using/not using set
}
Answer
function dublicateRemover(array) {
  let newarray = array.map((e) => {
    return e.toLowerCase();
  });
  let dupChars = newarray.filter((c, index) => {
    return newarray.indexOf(c) === index;
  });

  return dupChars;
}

function dublicateRemover(array) {
  const mySet = new Set();
  for (let elem of array) {
    mySet.add(elem.toLowerCase());
  }
  return [...mySet];
}

🟒 06 - Dublicate Finder

const nums = [1, 2, -2, 4, 5, 4, 7, 8, 7, 7];
console.log(dublicateFinder(nums)); //["4", "7"];

function dublicateFinder(arr) {
  //Write a function to get array of duplicate values in array.
}
Answer

version 1

function dublicateFinder(arr) {
  let result = arr.filter((e, index) => {
    return arr.indexOf(e) !== index;
  });
  return [...new Set(result)];
}

version 2

function dublicateFinder(arr) {
  return arr.reduce((acc, cur, i) => {
    if (arr.lastIndexOf(cur) !== i && !acc.includes(cur)) {
      acc.push(cur);
    }
    return acc;
  }, []);
}

🟑 07 - Aggregate

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;
}

🟒 08 - Union

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];
}

🟒 09 - Numberify

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);
  });
}

🟒 10 - Remove Item

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);
}

🟒 11 - Array Gen.

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;
}

🟒 12 - GPX

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);
}

🟒 13 - Vlookup

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;
}

🟒 14 - Odd index

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;
}

🟒 15 - Exclude

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;
    }
  });
}

🟒 16 - Senior

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";
  });
}

🟒 17 - Reduce Deposite

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);
}

🟒 18 - Titlecase

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);
}

🟒 19 - Trimmer

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();
}

🟑 20 - Chess Board

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;
}

🟒 21 - Filter Properties

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;
}

🟒 22 - Filter Out Properties

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;
}

🟒 23 - Unique Colors

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())];
}

πŸ”΄ 24 - DNA

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;
}

🟑 25 - Array of Indexes

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;
}

🟒 26 - Reduced Array

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;
  }, []);
}

🟒 27 - Common Items

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;
    }
  });
}

🟑 28 - Bulk Overlaping

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)];
}

🟒 29 - Anagrams

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;
}

🟒 30 - Sum Up to Zero

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;
}

🟒 31 - Objectify

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 solution
function objectify(arr1, arr2) {
  let obj = {};
  arr1.forEach((e, i) => {
    obj[e] = arr2[i];
  });
  return obj;
}
  1. More advanced technics
function objectify(arr1, arr2) {
  return Object.fromEntries(
    arr1.reduce((acc, __, i) => {
      acc.push([arr1[i], arr2[i]]);
      return acc;
    }, [])
  );
}

🟒 32 - Equal Arrays

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 approach
function 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;
}

πŸ”΄ 33 - Spam Detector

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;
}

🟒 34 - Reverse Array

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]);
}

🟒 35 - Reverse String

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("");
}

🟒 36 - Palindrome Word

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("");
}

🟑 37 - Sliding Sum

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;
}

About

πŸ”° InfiniteJS Tasks - Basic building 🧱 you must taste! πŸ”₯πŸ’

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published