DEV Community

Discussion on: Reverse a String - Four JavaScript Solutions

Collapse
 
bugmagnet profile image
Bruce Axtens

Going nuts here. More ideas, and for something as mundane as a reverse function. Monomania?

function flip3(string) {
  var result = Array(string.length);
  for (var i = string.length - 1, j = 0; i >= 0; i--, j++) {
    result[j] = string.charAt(i);
  }
  return result.join("");
}

function flip4(string) {
    var result = Array(string.length).fill(1);
    result.map(function (item,index) {
        var rhs = string.length - 1 - index;
        result[index] = string.charAt(index);
    });
    return result.join("");
}

Your mileage may vary on flip4's .fill() call. I'm having to use polyfills (long story) and if I don't fill the Array, .map() assumes that there's nothing there to work on.

I do have a couple of ideas yet to exorcise.