Essential JavaScript Algorithms You Must Know for Interviews
Essential JavaScript Algorithms You Must Know for Interviews
Write a function that reverses a given string.
function reverseString(str) {
return str.split('').reverse().join('');
}
reverseString("hello"); // Output: "olleh"
Create a function to check if a string is a palindrome.
function isPalindrome(str) {
return str === str.split('').reverse().join('');
}
isPalindrome("racecar"); // Output: true
Write a function to find the factorial of a given number.
function factorialize(num) {
if (num < 0) return -1;
else if (num === 0) return 1;
else return (num * factorialize(num - 1));
}
factorialize(5); // Output: 120
Create a function to find the length of the longest word in a sentence.
function findLongestWordLength(str) {
let longestWord = str.split(' ').reduce(function(longest, currentWord) {
return currentWord.length > longest.length ? currentWord : longest;
}, "");
return longestWord.length;
}
findLongestWordLength("The quick brown fox jumped over the lazy dog"); // Output: 6
Write a function that converts a sentence to title case.
function titleCase(str) {
return str.toLowerCase().replace(/(^|\s)\S/g, (match) => match.toUpperCase());
}
titleCase("i am learning javascript"); // Output: "I Am Learning JavaScript"
Create a function that returns an array containing the largest number from each sub-array.
function largestOfFour(arr) {
return arr.map(subArray => Math.max(...subArray));
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39]]); // Output: [5, 27, 39]
Write a function to check if a string ends with a given target string.
function confirmEnding(str, target) {
return str.slice(-target.length) === target;
}
confirmEnding("Bastian", "n"); // Output: true
Create a function that repeats a string n
times.
function repeatStringNumTimes(str, num) {
return num > 0 ? str.repeat(num) : "";
}
repeatStringNumTimes("abc", 3); // Output: "abcabcabc"
Write a function to truncate a string if it is longer than a given maximum string length.
function truncateString(str, num) {
return str.length > num ? str.slice(0, num) + "..." : str;
}
truncateString("A-tisket a-tasket A green and yellow basket", 8); // Output: "A-tisket..."
Create a function that looks through an array and returns the first element that passes a given test.
function findElement(arr, func) {
return arr.find(func);
}
findElement([1, 3, 5, 8, 9, 10], num => num % 2 === 0); // Output: 8
Essential JavaScript Algorithms You Must Know for Interviews