DEV Community

Bruce Axtens
Bruce Axtens

Posted on • Updated on

Reversing a string using a Generator

So there's this Michiel Hendriks who says, "I'm looking for the next person to one-up this" and so here I am one-upping myself.

Here we reverse the string using a Generator to iterate backwards through the string and hand ball each character to an array that gets .join()ed at the end.

function Bruce_ReverseGenerator(string) {
  function* reverseGenerator(string) {
    let str = string;
    let index = str.length - 1;
    while (true)
      yield str.charAt(index--);
  }

  let result = [];
  const gen = reverseGenerator(string); 
  var ch;
  while (ch = gen.next().value) {
    result.push(ch);
  }
  return result.join("");
}
Enter fullscreen mode Exit fullscreen mode

Yep, decorated to run in the testing frame and giving surprisingly good results, viz:

C:\TMP>timer.ly /TIMES:1000
Sarah_ForOf                 1502.905 ticks
Bruce_CharAt                2646.537 ticks
Sarah_SplitReverseJoin      2715.699 ticks
Bruce_Recursive2            2786.771 ticks
Nathanael_SplitReverseJoin  3104.762 ticks
Bruce_Recursive1            3112.511 ticks
Theophanis_SplitFor         3208.017 ticks
Sarah_Reduce                3227.539 ticks
Theophanis_SplitFor_Bruced  3706.581 ticks
Sarah_Recursive             3810.085 ticks
Bruce_ArrayApplyMap         5318.65 ticks
Bruce_ReverseGenerator      7354.585 ticks
Bruce_MapSortMap            9637.046 ticks
Bruce_CharAt2               13913.316 ticks
Bruce_RegReverse            490151.264 ticks
Enter fullscreen mode Exit fullscreen mode

Top comments (0)