Add Range.compare

This commit is contained in:
Nathan Sobo 2013-04-24 16:19:59 -06:00
parent aef34c11b7
commit df6feab346
2 changed files with 25 additions and 0 deletions

View File

@ -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]]

View File

@ -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`.