DEV Community

Bruce Axtens
Bruce Axtens

Posted on • Edited on

2

Reversing a string using an ArrayBuffer

How many more ways are there to reverse a string in JavaScript? I was reading the friendly manual again and thought of another way.

The method is let down a little by the .map() at the end. I was rather hoping for a less pedestrian way of changing the ArrayBuffer back into normal text.

The other gotcha is that we're storing uint values, so prepare for mangled emojis.

function Bruce_ByteBuffer(string) {
  let buffer = new ArrayBuffer(string.length);
  let int8View = new Uint8Array(buffer);
  for (let i = 0, j = string.length - 1; i < string.length; i++, j--) {
    int8View[i] = string.charCodeAt(j);
  }
  return Array.prototype.slice.call(int8View).map(function (item) {
    return String.fromCharCode(item)
  }).join("");
}
Enter fullscreen mode Exit fullscreen mode

Speed-wise, using my framework, it's in the slower end of midrange.

Sarah_ForOf                 1997.262 ticks
Bruce_CharAt                3165.792 ticks
Sarah_SplitReverseJoin      3382.125 ticks
Bruce_Recursive2            3423.004 ticks
Theophanis_SplitFor         3765.074 ticks
Nathanael_SplitReverseJoin  3829.166 ticks
Bruce_Recursive1            3981.59 ticks
Sarah_Reduce                4272.548 ticks
Theophanis_SplitFor_Bruced  4310.981 ticks
Sarah_Recursive             4580.1 ticks
Bruce_ArrayApplyMap         6305.892 ticks
Bruce_ReverseGenerator      8994.98 ticks
Bruce_MapSortMap            11262.885 ticks
Bruce_ByteBuffer            15190.07 ticks
Bruce_CharAt2               17016.049 ticks
Bruce_IteratorReverse       103529.193 ticks
Bruce_RegReverse            582476.836 ticks
Enter fullscreen mode Exit fullscreen mode

Imagine monitoring actually built for developers

Billboard image

Join Vercel, CrowdStrike, and thousands of other teams that trust Checkly to streamline monitor creation and configuration with Monitoring as Code.

Start Monitoring

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay