DEV Community

Bruce Axtens
Bruce Axtens

Posted on • Edited on

Reversing a string using .from

I was rather hoping that this series would finish with .some but here we are again reversing a string. This time, we're using Array.from().

This is the ES6 version

const Bruce_ArrayFrom = (str, buf = []) => {
  Array.from(str, (itm) =>
    buf.unshift(itm)
  );
  return buf.join("");
}
Enter fullscreen mode Exit fullscreen mode

and the ES3 version, thanks to Babel

var Bruce_ArrayFromES3 = function Bruce_ArrayFromES3(str) {
  var buf =
    arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  Array.from(str, function(itm) {
    return buf.unshift(itm);
  });
  return buf.join("");
};

Enter fullscreen mode Exit fullscreen mode

In terms of speed, both are awful, both sitting down the bottom of the list. Only the RegExp version is slower. Intriguingly, the ES3 version is slower than the ES6 (for reasons unknown.)

Hopefully, that's the end of reversing strings with JavaScript. Like Perl, there's more than one way to do it though some ways are better than others.

Top comments (4)

Collapse
 
adam_cyclones profile image
Adam Crockett πŸŒ€

Is there not an reverse method on the string prototype, there is on the array prototype.

Collapse
 
bugmagnet profile image
Bruce Axtens

As it turns out, no, there is no String.prototype.reverse(). For ages therefore people have been using (usually) var reversedString = "string".split("").reverse().join("") and other approaches.

My 'series' (for want of a better word) came out of Sarah Chima's original posting discussing the issue and offering some options.

Collapse
 
adam_cyclones profile image
Adam Crockett πŸŒ€

In that case, nice! Good to measure perf as well nice touch.

Thread Thread
 
bugmagnet profile image
Bruce Axtens

Thank you.