Skip to content

Commit 1d06c4d

Browse files
committed
Optimize codes of #intersect
1 parent 6b966f4 commit 1d06c4d

File tree

2 files changed

+12
-9
lines changed

2 files changed

+12
-9
lines changed

multi-integer-range.ts

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -142,22 +142,23 @@ export class MultiRange {
142142
if (typeof value === 'undefined') {
143143
throw new TypeError('Invalid input');
144144
} else if (value instanceof MultiRange) {
145-
let result = new MultiRange();
146-
let that = new MultiRange(value);
145+
let result = [];
147146
let jstart = 0; // used for optimization
148147
for (let i = 0; i < this.ranges.length; i++) {
149-
for (let j = jstart; j < that.ranges.length; j++) {
150-
if (this.ranges[i][0] <= that.ranges[j][1] && this.ranges[i][1] >= that.ranges[j][0]) {
148+
let r1 = this.ranges[i];
149+
for (let j = jstart; j < value.ranges.length; j++) {
150+
let r2 = value.ranges[j];
151+
if (r1[0] <= r2[1] && r1[1] >= r2[0]) {
151152
jstart = j;
152-
let min = Math.max(this.ranges[i][0], that.ranges[j][0]);
153-
let max = Math.min(this.ranges[i][1], that.ranges[j][1]);
154-
result.appendRange(min, max);
155-
} else if (this.ranges[i][1] < that.ranges[j][0]) {
153+
let min = Math.max(r1[0], r2[0]);
154+
let max = Math.min(r1[1], r2[1]);
155+
result.push([min, max]);
156+
} else if (r1[1] < r2[0]) {
156157
break;
157158
}
158159
}
159160
}
160-
this.ranges = result.ranges;
161+
this.ranges = result;
161162
return this;
162163
} else {
163164
return this.intersect(new MultiRange(value));

test/multi-integer-range.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,8 @@ describe('MultiRange', function() {
130130
t(mr(r2).intersect(r1), expected);
131131
}
132132
t2('1-5', '8', '');
133+
t2('5-100', '1,10,50,70,80,90,100,101', '10,50,70,80,90,100');
134+
t2('5-100', '1-10,90-110', '5-10,90-100');
133135
t2('30-50,60-80,90-120', '45-65,75-90', '45-50,60-65,75-80,90');
134136
t2('10,12,14,16,18,20', '11,13,15,17,19,21', '');
135137
t2('10,12,14,16,18,20', '10,12,14,16,18,20', '10,12,14,16,18,20');

0 commit comments

Comments
 (0)