In front-end development, there is a function called Math.random()
, which returns a random number between 0 and 1.
If we want to get a random color in actual development, what should we do?
First, use Math.random()
to get a number. Numbers have a toString()
function, which can convert numbers to strings. The key is that the toString()
function can take a conversion base. For example, Math.random().toString(2)
will give us the binary representation.
Colors are represented in hexadecimal, so we can pass 16 as the base.
Let's simplify it.
Let's encapsulate it into a function.
But there is a problem with this approach. Since the random number is between 0 and 1, if it is 0.5 or similar, the converted string will not have enough digits, which does not meet the requirements of a color.
In such cases, we need to manually append the missing digits to the end of the string. We can use padEnd()
for this.
This function will generate a random color. It can also generate random strings using Math.random().toString(36)
. The 36 base consists of 10 digits and 26 letters.
Let's encapsulate it into a function.
We can also specify the length of the string.
But generating strings in this way has limitations. The length of the generated random number is fixed. If the specified length exceeds the generated length, it will append too many custom characters at the end, which is not what we want for a random string.
If we count, we will find that the typical length of a randomly generated string is 11 digits. So let's modify the function recursively.
Now it can support longer strings.
function randomString(len) {
if (len <= 11) {
return Math.random().toString(36).slice(2, 2 + len).padEnd(len, '0');
} else {
return randomString(11) + randomString(len - 11)
}
}
console.log(randomString(100))