DEV Community

Discussion on: 1 line of code: How to reverse a string

Collapse
 
frankwisniewski profile image
Frank Wisniewski • Edited

the fastest solution in one line:

const reverseString=([firstChar,...str])=>firstChar?reverseString(str)+firstChar:''  
Enter fullscreen mode Exit fullscreen mode

It's a nice game to write functions in one line. But nothing more...

const areverseString=([firstChar,...str])=>firstChar?areverseString(str)+firstChar:''
//duration of 1.000.000 calls = 478 ms 

const breverseString = str => [...str].reverse().join("");
//duration of 1.000.000 calls = 1210 ms 

const creverseString = str => [...str].reduce((a,c) => c.concat(a));
//duration of 1.000.000 calls = 943 ms 

//now the classical way....
const reverseString = function (str) {
  let length = str.length
  let reverse = ''
  for (let i = 0; i<length; i++ ){
    reverse = str[i] + reverse
  }
  return reverse
}
//duration of 1.000.000 calls = 210 ms 

let start = performance.now()  
for (let y=1; y<1000000 ;y++){
  reverseString('Sauerkrauttopf');
}
let duration = performance.now() - start;
console.log(duration)
Enter fullscreen mode Exit fullscreen mode