Using .reverse()
function reverse(str) {
// const arr = str.split("");
const arr = Array.from(str);
return arr.reverse().join("");
}
Using .reduce()
function reverse(str) {
return str.split("").reduce((result, letter) => {
return letter + result;
}, "");
}
Using for... of
function reverse(str) {
let revStr = "";
for (let letter of str) {
revStr = letter + revStr;
}
return revStr;
}
Using a for() loop
function reverse(str) {
const arr = str.split("");
const rev = [];
for (var i = arr.length - 1; i >= 0; i--) {
rev.push(arr[i]);
}
return rev.join("");
}
Using a while() loop
function reverse(str) {
let count = str.length - 1;
let revStr = "";
while (count >= 0) {
revStr += str.charAt(count);
count -= 1;
}
return revStr;
}
Tests.
test('Reverse function exists', () => {
expect(reverse).toBeDefined();
});
test('Reverse reverses a string', () => {
expect(reverse('abcd')).toEqual('dcba');
});
test('Reverse reverses a string', () => {
expect(reverse(' abcd')).toEqual('dcba ');
});