Skip to content

Commit

Permalink
fix(intervals): update compare() to consider openness, add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Nov 12, 2019
1 parent d301628 commit 995b32a
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
11 changes: 10 additions & 1 deletion packages/intervals/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,8 +165,15 @@ export class Interval
return new Interval(this.l, this.r, this.lopen, this.ropen);
}

/**
* Compares this interval with `i` and returns a comparator value
* (-1, 0 or 1). Comparison order is: LHS, RHS, openness.
*
* @param i
*/
compare(i: Readonly<Interval>) {
if (this === i) return 0;
let c: number;
return this.l < i.l
? -1
: this.l > i.l
Expand All @@ -175,7 +182,9 @@ export class Interval
? -1
: this.r > i.r
? 1
: 0;
: (c = ~~this.lopen - ~~i.lopen) === 0
? ~~i.ropen - ~~this.ropen
: c;
}

equiv(i: any) {
Expand Down
11 changes: 11 additions & 0 deletions packages/intervals/test/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,4 +72,15 @@ describe("intervals", () => {
assert(a.intersection(i("[100..101]"))!.equiv(i("[100..100]")), "i18");
assert(a.intersection(i("(100..101]")) === undefined, "i19");
});

it("compare", () => {
const a = i("[0..1]");
const b = i("(0..1]");
const c = i("[0..1)");
const d = i("(0..1)");
assert.equal(a.compare(a), 0, "aa");
assert.equal(a.compare(b), -1, "ab");
assert.equal(a.compare(c), 1, "ac");
assert.equal(a.compare(d), -1, "ad");
});
});

0 comments on commit 995b32a

Please sign in to comment.