UNPKG

random-integral

Version:
51 lines (39 loc) 1.03 kB
'use strict'; var clamp = require('clamp'); var toInteger = require('to-integer'); var MAX_SAFE_INT = require('max-safe-int'); var MIN_SAFE_INT = -MAX_SAFE_INT; function fixme(val, min, max, isMin) { if (typeof val !== 'number') { val = toInteger(val); } if (isNaN(val) || !isFinite(val)) { return isMin ? min : max; } return clamp(val, min, max); } module.exports = function (options) { if (options) { // for speed up if (!options.inspected) { options.min = fixme(options.min, MIN_SAFE_INT, MAX_SAFE_INT, true); options.max = fixme(options.max, MIN_SAFE_INT, MAX_SAFE_INT, false); } } else { options = { min: MIN_SAFE_INT, max: MAX_SAFE_INT }; } var min = options.min; var max = options.max; // swap to variables // ref: http://stackoverflow.com/a/16201688 if (min > max) { min = min ^ max; max = min ^ max; min = min ^ max; } return Math.round(Math.random() * (max - min)) + min; }; module.exports.fixme = fixme;