random.js 754 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. //
  2. // Randomised testing helpers from OT.js:
  3. // https://github.com/Operational-Transformation/ot.js/blob/
  4. // 8873b7e28e83f9adbf6c3a28ec639c9151a838ae/test/helpers.js
  5. //
  6. 'use strict'
  7. function randomInt(n) {
  8. return Math.floor(Math.random() * n)
  9. }
  10. function randomString(n) {
  11. let str = ''
  12. while (n--) {
  13. if (Math.random() < 0.15) {
  14. str += '\n'
  15. } else {
  16. const chr = randomInt(26) + 97
  17. str += String.fromCharCode(chr)
  18. }
  19. }
  20. return str
  21. }
  22. function randomElement(arr) {
  23. return arr[randomInt(arr.length)]
  24. }
  25. function randomTest(numTrials, test) {
  26. return function () {
  27. while (numTrials--) test()
  28. }
  29. }
  30. exports.int = randomInt
  31. exports.string = randomString
  32. exports.element = randomElement
  33. exports.test = randomTest