DEV Community

Bruce Axtens
Bruce Axtens

Posted on • Edited on

7 1

Reversing a string using an Iterator

The problem with RTFM is that sometimes you find interesting things. So I'm reading through the documentation for the String object on MDN and discover how to instantiate an iterator.

function Bruce_IteratorReverse(string) {
  let iterator = string[Symbol.iterator]();
  let theChar = iterator.next();

  let result = [];
  while (!theChar.done) {
    result.unshift(theChar.value);
    theChar = iterator.next();
  }
  return result.join("");
}
Enter fullscreen mode Exit fullscreen mode

Put it in the test frame and run it for a 1000 iterations and come up with an average speed in C# Stopwatch Ticks. Not as bad as RegExp but down that end, viz:

Sarah_ForOf                 1954.52 ticks
Sarah_SplitReverseJoin      2628.535 ticks
Bruce_CharAt                2835.333 ticks
Theophanis_SplitFor         3088.03 ticks
Bruce_Recursive1            3442.696 ticks
Sarah_Reduce                3515.563 ticks
Bruce_Recursive2            3616.804 ticks
Nathanael_SplitReverseJoin  3751.542 ticks
Theophanis_SplitFor_Bruced  3815.779 ticks
Sarah_Recursive             4024.06 ticks
Bruce_ArrayApplyMap         5590.934 ticks
Bruce_ReverseGenerator      8441.915 ticks
Bruce_MapSortMap            10974.299 ticks
Bruce_CharAt2               14908.46 ticks
Bruce_IteratorReverse       93875.974 ticks
Bruce_RegReverse            524215.91 ticks
Enter fullscreen mode Exit fullscreen mode

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay