welsonjs/lib/rand.js

77 lines
1.8 KiB
JavaScript
Raw Normal View History

2022-01-15 12:37:07 +00:00
// rand.js
2022-01-08 17:52:19 +00:00
2022-01-15 10:37:49 +00:00
function randomize() {
return Math.random();
}
2022-01-08 16:42:00 +00:00
function getInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
2022-01-15 10:37:49 +00:00
return Math.floor(randomize() * (max - min + 1)) + min;
2022-01-08 16:42:00 +00:00
}
function one(arr) {
2022-01-08 17:42:45 +00:00
return arr[getInt(0, arr.length - 1)];
}
function makeString(length, characterNames) {
var result = '';
var characters = '';
for (var i = 0; i < characterNames.length; i++) {
switch (characterNames[i]) {
case 'uppercase':
characters += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
break;
case 'lowercase':
characters += 'abcdefghijklmnopqrstuvwxyz';
break;
case 'number':
characters += '0123456789';
break;
default:
characters += characterNames[i];
}
}
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
2022-01-15 10:37:49 +00:00
result += characters.charAt(Math.floor(randomize() * charactersLength));
2022-01-08 17:42:45 +00:00
}
return result;
2022-01-08 16:42:00 +00:00
}
2022-01-15 10:37:49 +00:00
// UUID v4
function uuidv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = randomize() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
2022-01-15 12:37:07 +00:00
function shuffle(arr) {
2022-01-15 12:35:14 +00:00
return arr.sort(function() {
return randomize() - 0.5;
});
}
2022-01-15 12:41:31 +00:00
function rotate(arr, i) {
return arr[i % arr.length];
2022-01-15 12:42:33 +00:00
}
2022-01-15 12:41:31 +00:00
2022-01-15 10:37:49 +00:00
exports.randomize = randomize;
2022-01-08 16:42:00 +00:00
exports.getInt = getInt;
exports.one = one;
2022-01-08 17:42:45 +00:00
exports.makeString = makeString;
2022-01-15 10:37:49 +00:00
exports.uuidv4 = uuidv4;
2022-01-15 12:37:07 +00:00
exports.shuffle = shuffle;
2022-01-15 12:41:31 +00:00
exports.rotate = rotate;
2022-01-08 16:42:00 +00:00
2022-01-15 12:42:56 +00:00
exports.VERSIONINFO = "Random Module (rand.js) version 0.3";
2022-01-08 16:42:00 +00:00
exports.global = global;
exports.require = global.require;