DEV Community

Bruce Axtens
Bruce Axtens

Posted on • Updated on

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 =;

  let result = [];
  while (!theChar.done) {
    theChar =;
  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

Top comments (0)