diff --git a/snippets/randomAlphaNumeric.md b/snippets/randomAlphaNumeric.md new file mode 100644 index 000000000..27a02f569 --- /dev/null +++ b/snippets/randomAlphaNumeric.md @@ -0,0 +1,27 @@ +--- +title: randomAlphaNumeric +tags: string,random,advanced +--- + +Returns a random string with the specified length. + +- Use `Array.from()` to create a new array with the specified `length`. +- Use `Math.random()` generate a random floating-point number, `Number.prototype.toString(36)` to convert it to an alphanumeric string. +- Use `String.prototype.slice(2)` to remove the integral part and decimal point from each generated number. +- Use `Array.prototype.some()` to repeat this process as many times as required, up to `length`, as it produces a variable-length string each time. +- Finally, use `String.prototype.slice()` to trim down the generated string if it's longer than the given `length`. + +```js +const randomAlphaNumeric = length => { + let s = ''; + Array.from({ length }).some(() => { + s += Math.random().toString(36).slice(2); + return s.length >= length; + }); + return s.slice(0, length); +}; +``` + +```js +randomAlphaNumeric(5); // '0afad' +``` diff --git a/snippets/randomString.md b/snippets/randomString.md deleted file mode 100644 index af7ff3f95..000000000 --- a/snippets/randomString.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -title: randomString -tags: math,random,beginner ---- - -Returns a random string of the specified length. - -- `Math.random()` generate a random number -- `ToString(16)` converts the number into a text string -- Finally, the `substr(2,8)` extracts chracters between the positions 2 and supplied length. - -```js -const randomString = (length) => Math.random().toString(20).substr(2, length) -``` - -```js -randomString(5); // '0afad' -```