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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

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

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