You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

rangeset.js 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. "use strict";
  2. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  3. if (k2 === undefined) k2 = k;
  4. Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
  5. }) : (function(o, m, k, k2) {
  6. if (k2 === undefined) k2 = k;
  7. o[k2] = m[k];
  8. }));
  9. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  10. Object.defineProperty(o, "default", { enumerable: true, value: v });
  11. }) : function(o, v) {
  12. o["default"] = v;
  13. });
  14. var __importStar = (this && this.__importStar) || function (mod) {
  15. if (mod && mod.__esModule) return mod;
  16. var result = {};
  17. if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  18. __setModuleDefault(result, mod);
  19. return result;
  20. };
  21. Object.defineProperty(exports, "__esModule", { value: true });
  22. const _ = __importStar(require("lodash"));
  23. const assert = __importStar(require("assert"));
  24. function mergeIntervals(intervals) {
  25. const stack = [[-Infinity, -Infinity]];
  26. _.sortBy(intervals, (x) => x[0]).forEach((interval) => {
  27. const lastInterval = stack.pop();
  28. if (interval[0] <= lastInterval[1] + 1) {
  29. stack.push([lastInterval[0], Math.max(interval[1], lastInterval[1])]);
  30. }
  31. else {
  32. stack.push(lastInterval);
  33. stack.push(interval);
  34. }
  35. });
  36. return stack.slice(1);
  37. }
  38. class RangeSet {
  39. constructor() {
  40. this.reset();
  41. }
  42. reset() {
  43. this.ranges = [];
  44. }
  45. serialize() {
  46. return this.ranges
  47. .map((range) => range[0].toString() + '-' + range[1].toString())
  48. .join(',');
  49. }
  50. addRange(start, end) {
  51. assert.ok(start <= end, `invalid range ${start} <= ${end}`);
  52. this.ranges = mergeIntervals(this.ranges.concat([[start, end]]));
  53. }
  54. addValue(value) {
  55. this.addRange(value, value);
  56. }
  57. parseAndAddRanges(rangesString) {
  58. const rangeStrings = rangesString.split(',');
  59. rangeStrings.forEach((rangeString) => {
  60. const range = rangeString.split('-').map(Number);
  61. this.addRange(range[0], range.length === 1 ? range[0] : range[1]);
  62. });
  63. }
  64. containsRange(start, end) {
  65. return this.ranges.some((range) => range[0] <= start && range[1] >= end);
  66. }
  67. containsValue(value) {
  68. return this.containsRange(value, value);
  69. }
  70. }
  71. exports.default = RangeSet;
  72. //# sourceMappingURL=rangeset.js.map