UNPKG

shuyar-util

Version:

Some useful function or tools in development.

85 lines (70 loc) 2.23 kB
;(function () { /** * Created by Galen Sheen * @Desc 生成随机字符串 */ // Reference to the global object var root = this; // Numerics var nums = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' ]; // Lower case letters var lowers = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' ]; // Upper case letters var uppers = [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' ]; // Symbols var symbols = [ '!', '$', '@', '#', '%', '^', '&', '*' ]; function randomIndex(n) { return Math.floor(Math.random() * n); } // The main function to generate random string according the length and array of charaters function randomGen (n, chars) { n || (n = 8); var str = ''; for (var i = 0, len = chars.length; i < n; i++) { str += chars[randomIndex(len)]; } return str; } // Main random method var random = { number: function (n) { return randomGen(n, nums); }, lower: function (n) { return randomGen(n, lowers); }, upper: function (n) { return randomGen(n, uppers); }, letter: function (n) { var arr = lowers.concat(uppers); return randomGen(n, arr); }, alpha: function (n) { var arr = lowers.concat(uppers).concat(nums); return randomGen(n, arr); }, any: function (n) { var arr = lowers.concat(uppers).concat(nums).concat(symbols); return randomGen(n, arr); } } // Exports, check the env, node or browser if (typeof module !== 'undefined' && module.exports) { // Node env module.exports = random; } else if (typeof window !== 'undefined') { // Browser env root.random = random; } else { return random; } }).call(this);