const reverseString = str => [...str].reverse().join("");
Returns the reversed string.
The repository & npm package
You can find the all the utility functions from this series at github.com/martinkr/onelinecode
The library is also published to npm as @onelinecode for your convenience.
The code and the npm package will be updated every time I publish a new article.
Follow me on Twitter: @martinkr and consider to buy me a coffee
Photo by zoo_monkey on Unsplash
Top comments (10)
I was just messing around with a few ways to do this, and timed this approach. To my surprise, it seems to be twice as fast as your example on my setup :/
Heck, this might even be a little quicker than that on larger strings
If this was about speed, it would probably be faster not to use an array at all:
Actually, everything I tried that didn't use an array was slower, because the built in functions likely map to better compiled code.
Uncaught ReferenceError: r is not defined...
My bad, typed that on the cellphone.
The function doesn't return anything...it seems to be an old turntable phone..;-)
I'll try it later when I have my PC.
Found the issue, but it is indeed slower.
thanks to everyone for the efortand the thoughtful contributions.
I setup a benchmark with all one-line contributions. For me, on chrome, the article's function is the fastest with 400 ops/s.
Interested to see which results you guys get
I prefer to hard code my reversed strings 🥁
the fastest solution in one line:
It's a nice game to write functions in one line. But nothing more...