DEV Community

Bruce Axtens
Bruce Axtens

Posted on • Edited on

1

Reversing a string using .some

I was looking at some of my Google Apps Script code that uses .some() and I thought (as one does), I wonder if that could be used to reverse a string.

This is about as pure ES6 as I can get it.

const Bruce_SomeReverse = (s, rev = "") => {
  s.split("").some((itm, idx, arr) => {
    rev = rev + arr[arr.length - 1 - idx];
  });
  return rev;
}
Enter fullscreen mode Exit fullscreen mode

Using Babel I've converted it to ES3 should anyone want to use it there (like in Google Apps Script).

"use strict";

var Bruce_SomeReverse = function Bruce_SomeReverse(s) {
  var rev =
    arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
  s.split("").some(function(itm, idx, arr) {
    rev = rev + arr[arr.length - 1 - idx];
  });
  return rev;
};
Enter fullscreen mode Exit fullscreen mode

Performance-wise this method is very speedy, in the top 5 (using my speed tester):

Sarah_ForOf                 986.973 ticks
Bruce_Recursive2            2664.535 ticks
Bruce_SomeReverse_ES3       3085.19 ticks
Bruce_Recursive1            3209.047 ticks
Bruce_SomeReverse           3312.393 ticks
Enter fullscreen mode Exit fullscreen mode

As seems often to be the case, at least in my V8 instance, the ES3 version is the faster.

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

Top comments (0)

Billboard image

Imagine monitoring that's actually built for developers

Join Vercel, CrowdStrike, and thousands of other teams that trust Checkly to streamline monitor creation and configuration with Monitoring as Code.

Start Monitoring

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay