DEV Community

Bruce Axtens
Bruce Axtens

Posted on

Random strings generator

I was converting a ECMAScript 3 function to ES6's "fat-arrow" format. It certainly abbreviates.

function randomString(c) {
  for (var a = [], b = 0; b < c; b++) {
    a.push(Math.floor(36 * Math.random()).toString(36));
  }
  return a.join("");
}
Enter fullscreen mode Exit fullscreen mode

was how it was originally defined. Now it looks like this:

const randomString = c => Array(c).fill(0).map(function (itm, idx) {
    return Math.floor(36 * Math.random()).toString(36);
  }).join("");
Enter fullscreen mode Exit fullscreen mode

The ES3 form is slightly faster than the ES6 version but but only by about 40 nanoseconds. The fill and map probably have overheads that the for doesn't.

(a few minutes later)

Have made the ES6 version a bit more terse:

const ES6randomString = c => Array(c)
  .fill(0)
  .map(() => Math.floor(36 * Math.random()).toString(36))
  .join("");
Enter fullscreen mode Exit fullscreen mode

But sadly the ES3 version is still faster. Any suggestions?

Top comments (0)