Skip to content

Instantly share code, notes, and snippets.

@Pablissimo
Created January 28, 2013 19:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Pablissimo/4658214 to your computer and use it in GitHub Desktop.
Save Pablissimo/4658214 to your computer and use it in GitHub Desktop.
Mucking about with .NET in 10 spare minutes to emulate some of sometimes.rb's functionality in a horribly non-.NET way
using System;
namespace Sometimes
{
class Program
{
static void Main(string[] args)
{
// Farting about with a .NET-esque toy version of sometimes.rb...
5.To(10).Times(() => Console.WriteLine("This'll get annoying"));
50.PercentOfTheTime(() => Console.WriteLine("Half and half"));
Console.ReadLine();
}
}
public static class SometimesExtensions
{
static Random _prng = new Random();
public static void PercentOfTheTime<T>(this T percent, Action action) where T : struct
{
double asDouble = Convert.ToDouble(percent) / 100.0;
if (asDouble < 0 || asDouble > 100)
{
throw new ArgumentException("Percentages have to be between 0 and 100");
}
if (_prng.NextDouble() < asDouble)
{
action();
}
}
public static void Times<T>(this Range<T> range, Action action) where T : struct
{
long from = Convert.ToInt64(range.From);
long to = Convert.ToInt64(range.To);
long spread = Math.Max(from, to) - Math.Min(from, to);
long iterations = Math.Min(from, to) + (long) (_prng.NextDouble() * (spread + 1));
for (long i = 0; i < iterations; i++)
{
action();
}
}
public static Range<T> To<T>(this T from, T to) where T : struct
{
return new Range<T>(from, to);
}
}
public class Range<T> where T : struct
{
public T From { get; private set; }
public T To { get; private set; }
public Range(T from, T to)
{
this.From = from;
this.To = to;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment