Last active
April 27, 2020 00:22
-
-
Save deemaxx/dacd3e02175f880971a3ecc72931f2df to your computer and use it in GitHub Desktop.
Reverse a String with different methods.
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
// Reverse a string with the Array.reverse() method, recursive method, the for loop method, or the ES6+ method. | |
const revString = 'olraC si eman ym iH' | |
/** | |
* Reversing a string with a for loop | |
* @param str | string | |
* @returns | string | |
*/ | |
function forLoopStringReversal(str) { | |
let newStr = ''; | |
for (let i = 0; i < str.length; i++) { | |
newStr = str[i] + newStr; | |
} | |
return newStr; | |
} | |
forLoopStringReversal(revString); // 'Hi my name is Carlo' | |
// time complexity: O(n) | |
// space complexity: O(1) | |
/** | |
* Reversing a string with the Array.reverse() method | |
* @param str | string | |
* @returns | string | |
*/ | |
function stringReversal(str) { | |
return str.split('').reverse().join(''); | |
} | |
stringReversal(revString); // 'Hi my name is Carlo' | |
// time complexity: O(n) | |
// space complexity: O(1) | |
/** | |
* Reversing a string with recursion | |
* @param str | string | |
* @returns | string | |
*/ | |
function recursiveStringReversal(str) { | |
let newStr = ''; | |
if (!str.length) return ''; | |
newStr = recursiveStringReversal(str.slice(1)) + str[0]; | |
return newStr; | |
} | |
recursiveStringReversal(revString); // 'Hi my name is Carlo' | |
// time complexity: O(n) | |
// space complexity: O(1) | |
/** | |
* Using ES6+ syntax | |
* @param str | string | |
* @returns | string | |
*/ | |
const es6StringReversal = str => [...str].reverse().join(''); | |
es6StringReversal(rev); | |
// time complexity: O(n) | |
// space completxity: O(1) | |
// See jsPerf for performance results: https://jsperf.com/stringreversal |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment