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.

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

Top comments (0)

👋 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