From df6feab34613c455e45404d443dd9895a128eac1 Mon Sep 17 00:00:00 2001 From: Nathan Sobo Date: Wed, 24 Apr 2013 16:19:59 -0600 Subject: [PATCH] Add Range.compare --- spec/app/range-spec.coffee | 8 ++++++++ src/app/range.coffee | 17 +++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/spec/app/range-spec.coffee b/spec/app/range-spec.coffee index c73111ace..24460a064 100644 --- a/spec/app/range-spec.coffee +++ b/spec/app/range-spec.coffee @@ -33,6 +33,14 @@ describe "Range", -> expect(new Range([2, 1], [3, 10]).union(new Range([2, 5], [3, 1]))).toEqual [[2, 1], [3, 10]] expect(new Range([2, 5], [3, 1]).union(new Range([2, 1], [3, 10]))).toEqual [[2, 1], [3, 10]] + describe ".compare(otherRange)", -> + it "sorts earlier ranges first, and larger ranges first if both ranges start at the same place", -> + expect(new Range([1, 1], [2, 10]).compare(new Range([2, 1], [3, 10]))).toBe -1 + expect(new Range([2, 1], [3, 10]).compare(new Range([1, 1], [2, 10]))).toBe 1 + expect(new Range([1, 1], [3, 10]).compare(new Range([1, 1], [2, 10]))).toBe -1 + expect(new Range([1, 1], [2, 10]).compare(new Range([1, 1], [3, 10]))).toBe 1 + expect(new Range([1, 1], [3, 10]).compare(new Range([1, 1], [3, 10]))).toBe 0 + describe ".translate(startPoint, endPoint)", -> it "returns a range translates by the specified start and end points", -> expect(new Range([1, 1], [2, 10]).translate([1])).toEqual [[2, 1], [3, 10]] diff --git a/src/app/range.coffee b/src/app/range.coffee index 72e1ede1a..d4e7f2ba2 100644 --- a/src/app/range.coffee +++ b/src/app/range.coffee @@ -71,6 +71,23 @@ class Range other.start.isEqual(@start) and other.end.isEqual(@end) + # Returns an integer (-1, 0, 1) indicating whether this range is less than, equal, + # or greater than the given range when sorting. + # + # Ranges that start earlier are considered "less than" ranges that start later. + # If ranges start at the same location, the larger range sorts before the smaller + # range. + # + # other - A {Range} to compare against. + # + # Returns a {Number}, either -1, 0, or 1. + compare: (other) -> + other = Range.fromObject(other) + if value = @start.compare(other.start) + value + else + other.end.compare(@end) + # Public: Identifies if the `Range` is on the same line. # # In other words, if `start.row` is equal to `end.row`.