UNPKG

1.11 kBJavaScriptView Raw
1/**
2 * random table string and table length.
3 */
4var TABLE = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
5 TABLE_LEN = TABLE.length;
6
7
8/**
9 * generate random string from template.
10 *
11 * replace for placeholder "X" in template.
12 * return template if not has placeholder.
13 *
14 * @param {String} template template string.
15 * @throws {TypeError} if template is not a String.
16 * @return {String} replaced string.
17 */
18function generate(template) {
19 var match, i, len, result;
20
21 if (typeof template !== 'string') {
22 throw new TypeError('template must be a String: ' + template);
23 }
24
25 match = template.match(/(X+)[^X]*$/);
26
27 // return template if not has placeholder
28 if (match === null) {
29 return template;
30 }
31
32 // generate random string
33 for (result = '', i = 0, len = match[1].length; i < len; ++i) {
34 result += TABLE[Math.floor(Math.random() * TABLE_LEN)];
35 }
36
37 // concat template and random string
38 return template.slice(0, match.index) + result +
39 template.slice(match.index + result.length);
40}
41
42
43/**
44 * export.
45 */
46module.exports = {
47 generate: generate
48};