Oh.. why? Why should we work on theoritical algo problems when we could develop the next Instagram or Salesforce.com?
Because, son - you have to learn the different paths to glory. Why take the longer path when it can be shorter?
That aside: let us look at multiple ways of reversing a string in Javascript.
The best and easiest way
Convert to array and back.
const txt = "abcxyz";
console.log(txt.split("").reverse().join(""));
Prove that I know ‘modern’ functions
Aka - use reducer to reverse.
const txt = "abcxyz";
const rev = [...txt].reduceRight((revStr, char) => (revStr += char));
console.log(rev); // zyxcba
Or, just use a for.
More of the same
Yep, more ESXX. Use a map.
const txt = "abcxyz";
const revArr = [...txt].map((_, char, arr) => arr[arr.length - 1 - char]);
console.log(revArr.join("")); // zyxcba
Be super object oriented in the wrong language
In fact you can use prototypes everywhere, but below is a cool implementation using RTL override. You may have to use browser console if you are unable to see this code in action in your favourite console.
String.prototype.reverse = function () {
return "\u202E" + this;
};
// RTL
var txt = "\u202E" + "abcxyz";
console.log("txt.reverse(): ", txt.reverse());