DEV Community

Bruce Axtens
Bruce Axtens

Posted on

Another random string generator

So here we are again generating random strings. I was doing this for a Google Apps Script project where I wanted random names for temporary Google Docs files. I wanted something short, pithy and ... well ... random. Obviously, it's not cryptographically random, but that's not the goal.

The following code was written for Deno, so it's got TypeScript markup in it. Also, I do all my GAS projects in TypeScript, with ts2gas in the workflow to convert to JavaScript before uploading to Google.

The script works by generating an Array with a parameter-controlled n slots in it. This gets filled with zero and then .map comes in to map each element to the base36 representation of a random number between 0 and 35. All that then gets .join-ed into a single n length string.

const randomChars = (n: number) =>
  Array(n).fill(0).map((elt: number) => {
    return Math.ceil(Math.random() * 35).toString(36);
  }).join("");

console.log(randomChars(Deno.args.length ? parseInt(Deno.args[0], 10) : 40));
Enter fullscreen mode Exit fullscreen mode

With the above called randomChars.ts one may invoke with

deno run randomChars.ts

and get something like this:

b3xavd4po2ryfvkyrkgi7j9bg35cdhhnq27fhv59
Enter fullscreen mode Exit fullscreen mode

or invoke with

deno run randomChars.ts 17

and get something like that:

hdvyeb1qo47ix3wcs
Enter fullscreen mode Exit fullscreen mode

Doubtless there are better ways of doing this, but it's working and it was cool to be able to use Deno to do it.

Oldest comments (0)