Basic Algorithm Scripting Flashcards
Reverse the provided string. You may need to turn the string into an array before you can reverse it. Your result must be a string. function reverseString(str) { } reverseString(“hello”);
function reverseString(str) { return str.split('').reverse().join(''); }
Return the factorial of the provided integer. If the integer is represented with the letter n, a factorial is the product of all positive integers less than or equal to n. Factorials are often represented with the shorthand notation n! For example: 5! = 1 * 2 * 3 * 4 * 5 = 120 function factorialize(num) { } factorialize(5);
function factorialize(num) { if (num === 0) { return 1; } return num \* factorialize(num-1); }
Notice at the first line we have the terminal condition, i.e a condition to check the end of the recursion. If num == 0, then we return 1, i.e. effectively ending the recursion and informing the stack to propagate this value to the upper levels. If we do not have this condition, the recursion would go on until the stack space gets consumed, thereby resulting in a Stack Overflow.
Return true if the given string is a palindrome. Otherwise, return false.You’ll need to remove all non-alphanumeric characters (punctuation, spaces and symbols) and turn everything lower case in order to check for palindromes. function palindrome(str) { } palindrome(“seesaw”);
// Using reverse and equality operator on string
function palindrome(str) { return str.toLowerCase().replace(/[^a-z|0-9]/g, "") === str.toLowerCase().replace(/[^a-z|0-9]/g,"").split('').reverse().join(''); }
// OR, using for loop and equality operator on array
function palindrome(str) { str = str.toLowerCase().replace(/[\W\_]/g, ''); for(var i = 0, len = str.length - 1; i \< len/2; i++) { if(str[i] !== str[len-i]) { return false; } } return true; }
Return the length of the longest word in the provided sentence.
Your response should be a number.
function findLongestWord(str) {
}
findLongestWord(“What if we try a super-long word such as otorhinolaryngology”);
// Using .map
function findLongestWord(str) { var myArray = str.split(' '); var longest = 0; myArray.map(function(word){ word.length \> longest ? longest = word.length : longest = longest; }); return longest; }
// OR, by using .reduce
function findLongestWord(s) { return s.split(' ') .reduce(function(x, y) { return Math.max(x, y.length) }, 0); }
Return the provided string with the first letter of each word capitalized. Make sure the rest of the word is in lower case.
For the purpose of this exercise, you should also capitalize connecting words like “the” and “of”.
function titleCase(str) {
}
// Using .map
function titleCase(str) { return str.toLowerCase().split(' ').map( function(word){ return word.charAt(0).toUpperCase() + word.slice(1); } ).join(' '); }
// OR, using .replace
function titleCase(str) { return str.toLowerCase() .replace(/( |^)[a-z]/g, (L) =\> L.toUpperCase()); }
- ( |^) matches a space character or beginning of the whole string (^).
- (L) => L.toUpperCase() - this is the callback function used on the characters that match the regex
Return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays.
function largestOfFour(arr) {
}
// Returning [0] index of .sort nested in .map
function largestOfFour(arr) { return arr.map(function(nested){ return nested.sort(function(a,b){ return a \> b ? -1 : 1; })[0]; }); }
// OR, return .reduce result nested in .map
function largestOfFour(arr) { return arr.map(function(group){ return group.reduce(function(prev, current) { return (current \> prev) ? current : prev; }, 0); }); }
Check if a string (first argument, str) ends with the given target string (second argument, target).
function confirmEnding(str, target) {
}
// Using the new .endsWith string method
function confirmEnding(str, target) { return str.endsWith(target); }
// OR, using substring
function confirmEnding(str, target) { return target === str.substring(-target.length); }
NOTE: substr() calculates the index of first matching character from the string’s end if the specified location is negative.
Repeat a given string (first argument) num times (second argument). Return an empty string if num is not a positive number.
function repeatStringNumTimes(str, num) {
}
// Using ternary operator and .repeat
function repeatStringNumTimes(str, num) { return num \> 0 ? str.repeat(num) : ''; }
// OR, using recursion
function repeatStringNumTimes(str, num) {
if(num < 0)
return “”;
if(num === 1)
return str;
else
return str + repeatStringNumTimes(str, num - 1);
}
Truncate a string (first argument) if it is longer than the given maximum string length (second argument). Return the truncated string with a … ending.
Note that inserting the three dots to the end will add to the string length.
However, if the given maximum string length num is less than or equal to 3, then the addition of the three dots does not add to the string length in determining the truncated string.
function truncateString(str, num) {
}
// If/Else solution
function truncateString(str, num) { if (str.length \<= num) { return str; } else { return str.slice(0, num \> 3 ? num - 3 : num) + '...'; } }
// OR, using ternary operator function truncateString(str, num) { return num \<= 3 ? str.substring(0,num) + '...' : ( num \>= str.length ? str : str.substr(0, num - 3) + '...' ); }
Write a function that splits an array (first argument) into groups the length of size(second argument) and returns them as a two-dimensional array.
function chunkArrayInGroups(arr, size) {
}
function chunkArrayInGroups(arr, size) { var newArr = []; var i = 0;
while (i < arr.length) {
newArr.push(arr.slice(i, i+size));
i += size;
}
return newArr;
}
Return the remaining elements of an array after chopping off n elements from the head.
The head means the beginning of the array, or the zeroth index.
// Using slice - slice returns the selected elements in a new array, orginal array is UNchanged. function slasher(arr, howMany) { arr = arr.slice(howMany,arr.length); return arr; }
// Using splice, splice returns the removed(non-selected) items in a new array, original array is changed.
function slasher(arr, howMany) { arr.splice(0, howMany); return arr; }
Return true if the string in the first element of the array contains all of the letters of the string in the second element of the array.
For example, [“hello”, “Hello”], should return true because all of the letters in the second string are present in the first, ignoring case.
The arguments [“hello”, “hey”] should return false because the string “hello” does not contain a “y”.
Lastly, [“Alien”, “line”], should return true because all of the letters in “line” are present in “Alien”.
function mutation(arr) {
}
// Using for loop
function mutation(arr) {
arr[0] = arr[0].toLowerCase();
arr[1] = arr[1].toLowerCase();
for(var i = 0; i \< arr[1].length; i++){ if( arr[0].indexOf( arr[1].charAt(i) ) === -1 ){ return false; } } return true; }
// OR, using .split and .every
function mutation(arr) { return arr[1].toLowerCase() .split('') .every(function(letter) { return arr[0].toLowerCase() .indexOf(letter) != -1; }); }
Remove all falsy values from an array.
Falsy values in JavaScript are false, null, 0, “”, undefined, and NaN.
function bouncer(arr) { return arr.filter(Boolean); }
You will be provided with an initial array (the first argument in the destroyer function), followed by one or more arguments. Remove all elements from the initial array that are of the same value as these arguments.
function destroyer(arr) {
}
function destroyer(arr) { var args = Array.from(arguments); args.shift();
return arr.filter(function(element) {
return args.indexOf(element) === -1;
});
}
Return the lowest index at which a value (second argument) should be inserted into an array (first argument) once it has been sorted. The returned value should be a number.
For example, getIndexToIns([1,2,3,4], 1.5) should return 1 because it is greater than 1 (index 0), but less than 2 (index 1).
Likewise, getIndexToIns([20,3,5], 19)should return 2 because once the array has been sorted it will look like [3,5,20] and 19 is less than 20 (index 2) and greater than 5 (index 1).
function getIndexToIns(arr, num) {
}
// Using .sort
function getIndexToIns(arr, num) {
arr.sort(function(a, b) {
return a - b;
});
for (var a = 0; a \< arr.length; a++) { if (arr[a] \>= num){ return parseInt(a); } }
return arr.length;
}
// Using .sort and .findIndex
function getIndexToIns(arr, num) { var index = arr.sort((curr, next) =\> curr \> next) .findIndex((currNum)=\> num \<= currNum); return index === -1 ? arr.length : index; }