DEV Community

loading...

Discussion on: Reverse a String - Four JavaScript Solutions

Collapse
bugmagnet profile image
Bruce Axtens • Edited

I'm not sure what you'd call this solution, but it does reverse the string:

var times = function (n, fn /*, args*/) {
  var args = [].slice.call(arguments).slice(1);
  for (var i = 0; i < n; i++) {
    fn.call(this, i, args);
  }
  return args[2];
}

var original = "lewd i did live - evil did i dwel";
var result = "";

var reversed = times(original.length, function (i, args) {
    args[2] = args[1].substr(i, 1) + args[2];
  }, original, result);

That's the first time I've written code that uses .call(). Won't be the last time!