Skip to content

Commit

Permalink
Merge pull request #12 from github/feat-add-compare
Browse files Browse the repository at this point in the history
feat: add .compare(a, b), .rcompare(a, b)
  • Loading branch information
mislav committed Jun 21, 2017
2 parents 0e30ea8 + fa36ce4 commit f2d9c93
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 0 deletions.
2 changes: 2 additions & 0 deletions README.md
Expand Up @@ -29,6 +29,8 @@ VersionSorter.rsort(versions) #=> reverse sorted array

VersionSorter.sort!(versions) # sort array in place
VersionSorter.rsort!(versions) # reverse sort array in place

VersionSorter.compare(version_a, version_b) #=> positive or negative number depending on which way to sort
```

<http://github.com/blog/521-speedy-version-sorting>
9 changes: 9 additions & 0 deletions ext/version_sorter/version_sorter.c
Expand Up @@ -232,11 +232,20 @@ rb_version_sort_r_bang(VALUE rb_self, VALUE rb_versions)
return rb_version_sort_1(rb_self, rb_versions, version_compare_cb_r);
}

static VALUE
rb_version_compare(VALUE rb_self, VALUE rb_version_a, VALUE rb_version_b)
{
struct version_number *version_a = parse_version_number(StringValuePtr(rb_version_a));
struct version_number *version_b = parse_version_number(StringValuePtr(rb_version_b));
return INT2NUM(version_compare_cb(&version_a, &version_b));
}

void Init_version_sorter(void)
{
VALUE rb_mVersionSorter = rb_define_module("VersionSorter");
rb_define_module_function(rb_mVersionSorter, "sort", rb_version_sort, 1);
rb_define_module_function(rb_mVersionSorter, "rsort", rb_version_sort_r, 1);
rb_define_module_function(rb_mVersionSorter, "sort!", rb_version_sort_bang, 1);
rb_define_module_function(rb_mVersionSorter, "rsort!", rb_version_sort_r_bang, 1);
rb_define_module_function(rb_mVersionSorter, "compare", rb_version_compare, 2);
}
10 changes: 10 additions & 0 deletions test/version_sorter_test.rb
Expand Up @@ -21,6 +21,10 @@ def test_sorts_versions_correctly

def test_sorts_versions_like_rubygems
versions = %w(1.0.9.b 1.0.9 1.0.10 2.0 3.1.4.2 1.0.9a 2.0rc2 2.0-rc1)
if (Gem.rubygems_version < Gem::Version.new('2.1.0'))
# Old versions of RubyGems cannot parse semver versions like `2.0-rc1`
versions.pop()
end
sorted_versions = versions.sort_by { |v| Gem::Version.new(v) }

assert_equal sorted_versions, VersionSorter.sort(versions)
Expand Down Expand Up @@ -91,6 +95,12 @@ def test_rsort_block
assert_equal [@version10, @version2, @version1], sorted
end

def test_compare
assert VersionSorter.compare("10.0", "1.0") > 0
assert VersionSorter.compare("10.0", "12.0") < 0
assert_equal 0, VersionSorter.compare("12.0", "12.0")
end

def shuffle(array)
array, result = array.dup, []
result << array.delete_at(rand(array.size)) until array.size.zero?
Expand Down

0 comments on commit f2d9c93

Please sign in to comment.