random.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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, newLine = true) {
  11. let str = ''
  12. while (n--) {
  13. if (newLine && 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. function randomSubset(arr) {
  31. const n = randomInt(arr.length)
  32. const subset = []
  33. const indices = []
  34. for (let i = 0; i < arr.length; i++) indices.push(i)
  35. for (let i = 0; i < n; i++) {
  36. const index = randomInt(indices.length)
  37. subset.push(arr[indices[index]])
  38. indices.splice(index, 1)
  39. }
  40. return subset
  41. }
  42. function randomComments(number) {
  43. const ids = new Set()
  44. const comments = []
  45. while (comments.length < number) {
  46. const id = randomString(10, false)
  47. if (!ids.has(id)) {
  48. comments.push({ id, ranges: [], resolved: false })
  49. ids.add(id)
  50. }
  51. }
  52. return { ids: Array.from(ids), comments }
  53. }
  54. exports.int = randomInt
  55. exports.string = randomString
  56. exports.element = randomElement
  57. exports.test = randomTest
  58. exports.comments = randomComments
  59. exports.subset = randomSubset