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.

Billboard image

Monitoring as code

With Checkly, you can use Playwright tests and Javascript to monitor end-to-end scenarios in your NextJS, Astro, Remix, or other application.

Get started now!

Top comments (0)

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

👋 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