December 27, 2009

C# Extension Methods For Ruby Integer Functions

I was wondering whether some of the integer functions in Ruby would be handy in C#, so I wrote a few extension methods for them. Thus you can write something like:

1.UpTo(5).Do(i =>
// do stuff like value = items[i];
// do more stuff with value
);

instead of:

for (var i = 1; i <= 5; i++)
{
// do stuff like value = items[i];
// do more stuff with value
}

There’s also:

10.DownTo(5).Do(i => ...);
3.Next();
5.Times(i => ... );

Not sure how useful these are, but if anything, the Times one is short yet expressive. I may end up using it.

The code and tests:
public static class RubyExtensions
{
public static UpToValues UpTo(this int start, int limit)
{
return new UpToValues { Start = start, Limit = limit };
}

public class UpToValues
{
public int Start { get; set; }
public int Limit { get; set; }
}

public static void Do(this UpToValues values, Action<int> block)
{
for (var i = values.Start; i <= values.Limit; i++)
{
block(i);
}
}

public static DownToValues DownTo(this int start, int limit)
{
return new DownToValues { Start = start, Limit = limit };
}

public class DownToValues
{
public int Start { get; set; }
public int Limit { get; set; }
}

public static void Do(this DownToValues values, Action<int> block)
{
for (var i = values.Start; i >= values.Limit; i--)
{
block(i);
}
}

public static void Times(this int value, Action<int> block)
{
for (var i = 0; i < value; i++)
{
block(i);
}
}

public static int Next(this int value)
{
return value + 1;
}
}


[TestFixture]
public class Tests
{
[Test]
public void UpToTest()
{
var result = 0;
1.UpTo(7).Do(i => result += 2);
Assert.AreEqual(14, result);
}

[Test]
public void UpToTest2()
{
var result = string.Empty;
5.UpTo(10).Do((i) => result += (i + " "));
Assert.AreEqual("5 6 7 8 9 10 ", result);
}

[Test]
public void DownToTest()
{
var result = 5;
10.DownTo(6).Do(i => result--);
Assert.AreEqual(0, result);
}

[Test]
public void DownToTest2()
{
var result = string.Empty;
5.DownTo(1).Do(i => result += (i + ".."));
Assert.AreEqual("5..4..3..2..1..", result);
}

[Test]
public void TimesTest()
{
var result = 0;
12.Times(i => result++);
Assert.AreEqual(12, result);
}

[Test]
public void TimesTest2()
{
var result = string.Empty;
5.Times(i => result += i);
Assert.AreEqual("01234", result);
}

[Test]
public void NextTest()
{
Assert.AreEqual(2, 1.Next());
Assert.AreEqual(0, (-1).Next());
Assert.AreEqual(-1, (-2).Next());
}
}

0 comments:

Post a Comment