DEV Community

Bruce Axtens
Bruce Axtens

Posted on

2

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.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

SurveyJS custom survey software

JavaScript UI Library for Surveys and Forms

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

View demo

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay