Last active
February 3, 2018 20:35
-
-
Save GreggSetzer/609db349226596a090e9414571b4a5e8 to your computer and use it in GitHub Desktop.
Javascript Interview Question: Reverse a string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
A few ways to reverse a string using JavaScript. | |
*/ | |
//Most direct solution | |
function reverse(str) { | |
return str.split('').reverse().join(''); | |
} | |
//Example using the Array.reduce helper. | |
function reverse(str) { | |
return str.split('').reduce((newStr, char) => char + newStr, ''); | |
} | |
//Example using recursion. | |
function reverse(str) { | |
if (str.length <= 1) { | |
return str; | |
} | |
return reverse(str.substr(1)) + str[0]; | |
} | |
//Jest test case | |
test('It should reverse the string.', () => { | |
expect(reverse('abc')).toEqual('cba'); | |
}); | |
//Try it | |
console.log(reverse('abc')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment