DEV Community

Bruce Axtens
Bruce Axtens

Posted on • Edited on

2

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.

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

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.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay