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("");
}
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
Top comments (0)