Write a function called reversit() that reverses a c string
Answers
. for loop
The most straightforward and one might say naive approach is to utilise for loop. In this approach we can use decrementing or incrementing loop to iterate through each letter of the string and create a new reversed string:
function reverse(str){
let reversed = "";
for (var i = str.length - 1; i >= 0; i--){
reversed += str[i];
}
return reversed;
}
ES6, however introduced a new for loop syntax, such as for … of. It eliminates possibilities of making lots of silly typos while declaring our for loop, and results in a much neater piece of code:
function reverse(str){
let reversed = "";
for(let char of str){
reversed = char + reversed;
}
return reversed;
}
2. reverse() method for arrays
In case when your interviewer didn’t specifically ask you to avoid using a built-in reverse() method you can should definitely take advantage of it. In JavaScript reverse() method exists only for arrays, so first we need to use split() to transform string into an array, then apply reverse() method and finally join() it all back together:
function reverse(str){
return str.split("").reverse().join("");
}
3. spread syntax (ES6) + reverse() method for arrays
ES6 introduces one more way for splitting our string into an array, and that is a spread operator […]. Even though this solution is similar to the previous one, I believe it’s worth mentioning, for it looks and works pretty great.
function reverse(str){
return [...str].reverse().join('');
}
4. reduce() method for arrays
One of the most unconventional approaches that I rarely see in reverse string discussions is using reduce() method. Once again it only works for arrays, so first we need to split our string, and then accumulate our values into an empty string that becomes a reverse of our original string by the end of this operation:
function reverse(str){
return str.split("").reduce((rev, char)=> char + rev, '');
}