Initial commit
[yaffs-website] / node_modules / randomatic / index.js
1 /*!
2  * randomatic <https://github.com/jonschlinkert/randomatic>
3  *
4  * This was originally inspired by <http://stackoverflow.com/a/10727155/1267639>
5  * Copyright (c) 2014-2015, Jon Schlinkert.
6  * Licensed under the MIT License (MIT)
7  */
8
9 'use strict';
10
11 var isNumber = require('is-number');
12 var typeOf = require('kind-of');
13
14 /**
15  * Expose `randomatic`
16  */
17
18 module.exports = randomatic;
19
20 /**
21  * Available mask characters
22  */
23
24 var type = {
25   lower: 'abcdefghijklmnopqrstuvwxyz',
26   upper: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
27   number: '0123456789',
28   special: '~!@#$%^&()_+-={}[];\',.'
29 };
30
31 type.all = type.lower + type.upper + type.number;
32
33 /**
34  * Generate random character sequences of a specified `length`,
35  * based on the given `pattern`.
36  *
37  * @param {String} `pattern` The pattern to use for generating the random string.
38  * @param {String} `length` The length of the string to generate.
39  * @param {String} `options`
40  * @return {String}
41  * @api public
42  */
43
44 function randomatic(pattern, length, options) {
45   if (typeof pattern === 'undefined') {
46     throw new Error('randomatic expects a string or number.');
47   }
48
49   var custom = false;
50   if (arguments.length === 1) {
51     if (typeof pattern === 'string') {
52       length = pattern.length;
53
54     } else if (isNumber(pattern)) {
55       options = {}; length = pattern; pattern = '*';
56     }
57   }
58
59   if (typeOf(length) === 'object' && length.hasOwnProperty('chars')) {
60     options = length;
61     pattern = options.chars;
62     length = pattern.length;
63     custom = true;
64   }
65
66   var opts = options || {};
67   var mask = '';
68   var res = '';
69
70   // Characters to be used
71   if (pattern.indexOf('?') !== -1) mask += opts.chars;
72   if (pattern.indexOf('a') !== -1) mask += type.lower;
73   if (pattern.indexOf('A') !== -1) mask += type.upper;
74   if (pattern.indexOf('0') !== -1) mask += type.number;
75   if (pattern.indexOf('!') !== -1) mask += type.special;
76   if (pattern.indexOf('*') !== -1) mask += type.all;
77   if (custom) mask += pattern;
78
79   while (length--) {
80     res += mask.charAt(parseInt(Math.random() * mask.length, 10));
81   }
82   return res;
83 };