Skip to content

Instantly share code, notes, and snippets.

@GreggSetzer
Last active February 3, 2018 20:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GreggSetzer/609db349226596a090e9414571b4a5e8 to your computer and use it in GitHub Desktop.
Save GreggSetzer/609db349226596a090e9414571b4a5e8 to your computer and use it in GitHub Desktop.
Javascript Interview Question: Reverse a string
/*
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