String.random() + prototype with optional parameters for creating random strings

Maybe I'm wrong but there is no fast way to create a random string right now. We have "Math.random()" but function but no String equivalent.

My Idea
A string.random() function that returns a random string based on the character set you provide in the first parameter with a length of what you put in the second parameter. It can also be a prototype that reorders a string randomly using the string itself as the character set. The first parameter on the prototype can be an optional length.

Use case:

() => `#${ String.random( '0123456789ABCDEF', 6 )}` 

// Or

() => `#${ '0123456789ABCDEF'.random( 6 ) }` 

// These should / would return a random HEX color, for example: '#E8AC3F'

Right now, as far as I know, the fastest way to do this without using a "hard to read" one-liner is something like this:

const letters = '0123456789ABCDEF'
let color = ''"

for ( let i = 0; i < 6; i += 1 )
{
        color += letters[ Math.floor( Math.random() * 16 ) ]
}

return `#${color}`

In these examples, I create hex colors, but it can be used for a lot more than that like creating simple random ID's, reorder letters of words to make a grammar test or quiz, automated testing...

I'm unfamiliar with how proposals work. I don't even know where to fact check if this isn't a thing already besides https://developer.mozilla.org/. If this doesn't belong here let me know.

See https://github.com/tc39/proposal-uuid

2 Likes