Skip to content

Commit 942099d

Browse files
committed
Add source codes
0 parents  commit 942099d

File tree

3 files changed

+55
-0
lines changed

3 files changed

+55
-0
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
.DS_Store

README.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Random String Generator
2+
3+
Returns a random string.
4+
5+
## examples
6+
7+
```JavaScript
8+
generateRandomString(10); // "hm57vp5J4r"
9+
generateRandomString(8, ["a","p","P","l","e"]); // "PalalPae"
10+
generateRandomString(16, "orange-peel") // "-ag-laagn-n-lra-"
11+
generateRandomString(); // "AgZPEhZVUZRKDSKRctlgx5iibRPdWN8jCOjLxpr8ZnVT9Y9fWl9syJP8gSXjUlr8"
12+
```
13+
14+
## params
15+
16+
- **`length` (optional)**: The length of random string. Default: `64`
17+
- **`charset` (optional)**: Characters used in random string. Default: `abcdefghijklmnoqprstuvwxyzABCDEFGHIJKLMNOQPRSTUVWXYZ0123456789`
18+
19+
## returns
20+
21+
Returns a string that includes randomly selected characters from the charset.

mod.ts

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* Generate random string.
3+
*
4+
* @param { number | undefined } length - The length of random string. Default: `64`
5+
* @param { string[] | string | undefined } charset - Characters used in random string. Default: `abcdefghijklmnoqprstuvwxyzABCDEFGHIJKLMNOQPRSTUVWXYZ0123456789`
6+
* @returns { string } Generated random string.
7+
*
8+
* @example
9+
* ```JavaScript
10+
* generateRandomString(10); // "hm57vp5J4r"
11+
* generateRandomString(8, ["a","p","P","l","e"]); // "PalalPae"
12+
* generateRandomString(16, "orange-peel") // "-ag-laagn-n-lra-"
13+
* generateRandomString(); // "AgZPEhZVUZRKDSKRctlgx5iibRPdWN8jCOjLxpr8ZnVT9Y9fWl9syJP8gSXjUlr8"
14+
* ```
15+
*/
16+
17+
export const generateRandomString = (
18+
length = 64,
19+
charset: string[] | string = [
20+
"a", "b", "c", "d", "e", "f", "g", "h", "i",
21+
"j", "k", "l", "m", "n", "o", "p", "q", "r",
22+
"s", "t", "u", "v", "w", "x", "y", "z", "A",
23+
"B", "C", "D", "E", "F", "G", "H", "I", "J",
24+
"K", "L", "M", "N", "O", "P", "Q", "R", "S",
25+
"T", "U", "V", "W", "X", "Y", "Z", "0", "1",
26+
"2", "3", "4", "5", "6", "7", "8", "9"
27+
]
28+
): string => {
29+
return Array.from(Array(length)).reduce((prev, curr) => {
30+
curr = prev + charset[Math.floor(Math.random() * charset.length)];
31+
return curr
32+
}, "");
33+
}

0 commit comments

Comments
 (0)