jiti-meet/modules/util/RandomUtil.js

73 lines
1.6 KiB
JavaScript
Raw Normal View History

2015-11-04 14:39:56 +00:00
/**
* @const
*/
var ALPHANUM = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
2015-11-03 19:21:25 +00:00
2015-11-06 00:51:23 +00:00
/**
* Hexadecimal digits.
* @const
*/
var HEX_DIGITS = '0123456789abcdef';
2015-11-03 19:21:25 +00:00
/**
2015-11-04 14:39:56 +00:00
* Generates random int within the range [min, max]
* @param min the minimum value for the generated number
2015-11-03 19:21:25 +00:00
* @param max the maximum value for the generated number
2015-11-04 14:39:56 +00:00
* @returns random int number
*/
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
/**
* Get random element from array or string.
* @param {Array|string} arr source
* @returns array element or string character
*/
function randomElement(arr) {
return arr[randomInt(0, arr.length -1)];
}
/**
* Generate random alphanumeric string.
* @param {number} length expected string length
* @returns {string} random string of specified length
*/
function randomAlphanumStr(length) {
var result = '';
for (var i = 0; i < length; i += 1) {
result += randomElement(ALPHANUM);
}
return result;
}
2015-11-03 19:21:25 +00:00
/**
* Exported interface.
*/
var RandomUtil = {
/**
2015-11-06 00:51:23 +00:00
* Returns a random hex digit.
* @returns {*}
2015-11-03 19:21:25 +00:00
*/
2015-11-06 00:51:23 +00:00
randomHexDigit: function() {
return randomElement(HEX_DIGITS);
2015-11-03 19:21:25 +00:00
},
/**
2015-11-06 00:51:23 +00:00
* Returns a random string of hex digits with length 'len'.
* @param len the length.
2015-11-03 19:21:25 +00:00
*/
2015-11-06 00:51:23 +00:00
randomHexString: function (len) {
var ret = '';
while (len--) {
ret += this.randomHexDigit();
}
return ret;
2015-11-06 21:45:34 +00:00
},
randomElement: randomElement,
randomAlphanumStr: randomAlphanumStr
2015-11-03 19:21:25 +00:00
};
module.exports = RandomUtil;