File size: 1,106 Bytes
bc20498
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
45
46
47
48
49
/**
 * random table string and table length.
 */
var TABLE = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
    TABLE_LEN = TABLE.length;


/**
 * generate random string from template.
 *
 * replace for placeholder "X" in template.
 * return template if not has placeholder.
 *
 * @param {String} template template string.
 * @throws {TypeError} if template is not a String.
 * @return {String} replaced string.
 */
function generate(template) {
  var match, i, len, result;

  if (typeof template !== 'string') {
    throw new TypeError('template must be a String: ' + template);
  }

  match = template.match(/(X+)[^X]*$/);

  // return template if not has placeholder
  if (match === null) {
    return template;
  }

  // generate random string
  for (result = '', i = 0, len = match[1].length; i < len; ++i) {
    result += TABLE[Math.floor(Math.random() * TABLE_LEN)];
  }

  // concat template and random string
  return template.slice(0, match.index) + result +
      template.slice(match.index + result.length);
}


/**
 * export.
 */
module.exports = {
  generate: generate
};