I was wondering if there's a need to split at all, because characters are accessible directly using String#charAt
.
This implementation (which is almost the same as yours - only with the split) should be among the fastest.
function reverse(str) {
var result = [];
for (var i = str.length - 1; i >= 0; i--) {
result.push(str.charAt(i));
}
return result.join("");
}
console.log(reverse("abcde"));
According to some benchmark, String concatenation is better optimized than Array.join
, it also makes the code cleaner:
function reverse(str) {
var result = "";
for (var i = str.length - 1; i >= 0; i--) {
result += str.charAt(i);
}
return result;
}
console.log(reverse("abcde"));
As a side-note, you can get creative by using Array.prototype.reduce
and allow JavaScript duck-type the String
as an Array
.
function reverse(str) {
return Array.prototype.reduce.call(str, function(result, c) {
return c + result;
}, "");
}
console.log(reverse("Hello world!"));
And going further you can make an ES6 one-liner:
let reverse = str => Array.prototype.reduce.call(str, (result, c) => c + result, "");
console.log(reverse("Hello world!"));
JSFiddle forked from @Andreas: https://jsfiddle.net/kazenorin/6shbv6hs/2/