-
Notifications
You must be signed in to change notification settings - Fork 0
/
randomStringGenerator.js
44 lines (34 loc) · 1.04 KB
/
randomStringGenerator.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
* Generate a random string of a certain length.
* This string is alpha numeric
* @param {number} length - Length of random string to generate
* @throws
* @returns {string}
*/
function randomStringGenerator(length) {
var randomString = '',
i = 0;
if (length <= 0) {
throw new Error("Positive non-zero length required");
}
/**
* Helper function that generates a random char
* @returns {string} 1-character string
*/
function randomCharGenerator() {
var numberOrLetter = Math.round(Math.random());
// Generate a number
if (numberOrLetter === 0) {
return String(Math.floor(Math.random() * 10));
}
// Generate a letter
return String.fromCharCode('a'.charCodeAt(0) +
Math.floor(Math.random() * 26));
}
while (i < length) {
randomString += randomCharGenerator();
i++;
}
return randomString;
}
module.exports = exports = randomStringGenerator;