DEV Community

Discussion on: 20 Killer JavaScript One Liners ☝️

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited
const rgbToHex = (...rgb)=>'#'+rgb.reduce((a,v)=>a+(256|v).toString(16).slice(1),'')
const rgbToHex = (...rgb)=>'#'+rgb.reduce((a,v)=>a+v.toString(16).padStart(2,0),'')

const randomHex = (a='facedb')=>[...a].reduce(x=>x+(a+0x3d00b615)[~~(Math.random()*16)],'#')
const randomHex = (f='reduce')=>[...f][f](a=>a+(~~(Math.random()*16)).toString(16),'#')
const randomHex = ()=>'#'+(~~(Math.random()*(1<<24))|1<<25).toString(16).slice(1)
const randomHex = ()=>'#'+(~~(Math.random()*(1<<24))).toString(16).padStart(6,0)
const randomHex = ()=>'#'+(~~(Math.random()*8**8)).toString(16).padStart(6,0)
// Anyone got any shorter?


const reverse = str=>[...str].reduce((a,v)=>v+a)

const isEven = x=>~x&1

const capitalize = ([a,...b])=>a.toUpperCase()+b.join('')
const capitalize = a=>a.replace(/./,a=>a.toUpperCase())
Enter fullscreen mode Exit fullscreen mode

😊

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

I made no claim to it being faster, but in this case the reduce method is almost twice as fast - jsbench.me/3tkttupth4/1 - at least on Chrome. On Firefox though, the situation is reversed. Different JS engines, different optimisations I guess

Collapse
 
webreflection profile image
Andrea Giammarchi

Faster !== Correct ... his string reverse breaks with code points, while [...str] doesn't.

Try it: OP reverse breaks the emoji with reverse('some 💩'); while this reduce suggestion doesn't.

Thread Thread
 
webreflection profile image
Andrea Giammarchi • Edited

P.S.

// this works fast and correct at the same time
const reverse = str => [...str].reverse().join('');
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
eioluseyi profile image
Emmanuel Imolorhe

In a bid to be obnoxious 😏 you could have shortened your code further by 2 characters 🌚

const reverse = str => [...str].reverse().join``;
Enter fullscreen mode Exit fullscreen mode
Collapse
 
lluismf profile image
Lluís Josep Martínez

But who has the need in the real world / real apps to reverse a string? Nobody.

Collapse
 
silverium profile image
Soldeplata Saketos

alternative reverse:

const reverse = str => [...str].reduceRight((a,v)=> a+v)
Enter fullscreen mode Exit fullscreen mode

:D