String Reversal
Write a function that when given a string, it returns the string in reverse.
A classic for loop would work here as well, but you are less likely to make syntactical mistakes with the for...of loop and you don't need to convert the string to an array.
function reverse(str) {
let reversed = '';
for (let char of str) {
reversed = character + reversed;
}
return reversed;
}
function reverse(str) {
return str.split('').reverse().join('');
}
Array.prototype.reverse() + Spread Operator
function reverse(str) {
return [...str].reverse().join('');
}
Spread operator + Array.prototype.reduce()
function reverse(str) {
return [...str].reduce((reversed, char) => char + reversed, '');
}
Palindromes
Write a function that determines if a string is a palindrome and returns a boolean. A palindrome is a string that reads the same forward and reverse.
Using any of the previous reversal methods
function palindrome(str) {
return str === [...str].reverse().join('');
}
function palindrome(str) {
return str === [...str].every((item, index) => {
return item === str[str.length - i - 1];
});
}
Positive/Negative Integer Reversal
Using Number.prototype.toString() and parseInt() to switch types and Math.sign() to handle positive and negative values
function intReversed(n) {
const nStr = n.toString();
const nRev = [...nStr].reverse().join('');
return parseInt(nRev) * Math.sign(n);
}