randInt.js 623 B

123456789101112131415161718
  1. var MIN_INT = require('../number/MIN_INT');
  2. var MAX_INT = require('../number/MAX_INT');
  3. var rand = require('./rand');
  4. /**
  5. * Gets random integer inside range or snap to min/max values.
  6. */
  7. function randInt(min, max){
  8. min = min == null? MIN_INT : ~~min;
  9. max = max == null? MAX_INT : ~~max;
  10. // can't be max + 0.5 otherwise it will round up if `rand`
  11. // returns `max` causing it to overflow range.
  12. // -0.5 and + 0.49 are required to avoid bias caused by rounding
  13. return Math.round( rand(min - 0.5, max + 0.499999999999) );
  14. }
  15. module.exports = randInt;