Skip to content

Commit

Permalink
Merge pull request #45 from atlemann/42-version.icomparable
Browse files Browse the repository at this point in the history
Add IComparable to Version for sorting in F#
  • Loading branch information
adamreeve authored Oct 12, 2019
2 parents 5ba45f9 + f8d86bc commit efe3e2e
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 2 deletions.
16 changes: 15 additions & 1 deletion src/SemVer/Version.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ namespace SemVer
/// <summary>
/// A semantic version.
/// </summary>
public class Version : IComparable<Version>, IEquatable<Version>
public class Version : IComparable<Version>, IComparable, IEquatable<Version>
{
private readonly string _inputString;
private readonly int _major;
Expand Down Expand Up @@ -200,6 +200,20 @@ public bool Equals(Version other)
return CompareTo(other) == 0;
}

// Implement IComparable
public int CompareTo(object obj)
{
switch (obj)
{
case null:
return 1;
case Version v:
return CompareTo(v);
default:
throw new ArgumentException("Object is not a Version");
}
}

// Implement IComparable<Version>
public int CompareTo(Version other)
{
Expand Down
51 changes: 50 additions & 1 deletion test/SemVer.Tests/VersionComparison.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using Xunit;
using System;
using System.Linq;
using Xunit;
using Xunit.Extensions;

namespace SemVer.Tests
Expand Down Expand Up @@ -100,6 +102,53 @@ public void NotLessThanOrEqual(string a, string b)
Assert.False(versionA <= versionB);
}

[Fact]
public void CompareTo()
{
var actual =
new []
{
"1.5.0",
"0.0.4",
"0.1.0",
"0.1.1",
"0.0.2",
"1.0.0"
}
.Select(v => new Version(v))
.Cast<IComparable>()
.OrderBy(x => x)
.Select(x => x.ToString());

var expected =
new[]
{
"0.0.2",
"0.0.4",
"0.1.0",
"0.1.1",
"1.0.0",
"1.5.0"
};

Assert.Equal(expected, actual);
}

[Fact]
public void CompareToNull()
{
var version = (IComparable) new Version("1.0.0");
var actual = version.CompareTo(null);
Assert.Equal(1, actual);
}

[Fact]
public void CompareToDifferentType()
{
var version = (IComparable) new Version("1.0.0");
Assert.Throws<ArgumentException>(() => version.CompareTo(new Object()));
}

// Comparison tests from npm/node-semver
[Theory]
[InlineData("0.0.0", "0.0.0-foo")]
Expand Down

0 comments on commit efe3e2e

Please sign in to comment.