Last active
October 28, 2015 14:28
-
-
Save infosaurus/18d216ddf471c9619f7d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.VisualStudio.TestTools.UnitTesting; | |
namespace Grades | |
{ | |
using CharacterGrade = Grade<char, int>; | |
using NumericGrade = Grade<int, int>; | |
[TestClass] | |
public class GradesTests | |
{ | |
[TestMethod] | |
public void GradeTest() | |
{ | |
var grade1 = new CharacterGrade('A', GradeSystems.Letters); | |
var grade2 = new NumericGrade(100, GradeSystems.Percentage); | |
Assert.AreEqual(grade2.Value, grade1.To<int, PercentageGradeSystem>().Value); | |
} | |
} | |
public class GradeSystems | |
{ | |
public static LetterGradeSystem Letters { get { return new LetterGradeSystem(); } } | |
public static PercentageGradeSystem Percentage { get { return new PercentageGradeSystem(); } } | |
} | |
public abstract class GradeSystem<TValue, TCommon> | |
{ | |
public abstract Grade<TCommon, TCommon> ToCommon(TValue value); | |
public abstract Grade<TValue, TCommon> FromCommon(Grade<TCommon, TCommon> common); | |
} | |
public class LetterGradeSystem : GradeSystem<char, int> | |
{ | |
public override Grade<int, int> ToCommon(char value) | |
{ | |
var index = char.ToUpper(value) - 64; | |
return new Grade<int, int>(100 - ((1 - index) * 20), GradeSystems.Percentage); | |
} | |
public override Grade<char, int> FromCommon(Grade<int, int> common) | |
{ | |
var character = (char)(common.Value + 64); | |
return new Grade<char, int>(character, GradeSystems.Letters); | |
} | |
} | |
public class PercentageGradeSystem : GradeSystem<int, int> | |
{ | |
public override Grade<int, int> ToCommon(int value) | |
{ | |
return new Grade<int, int>(value, new PercentageGradeSystem()); | |
} | |
public override Grade<int, int> FromCommon(Grade<int, int> common) | |
{ | |
return new Grade<int, int>(common.Value, new PercentageGradeSystem()); | |
} | |
} | |
public class Grade<TValue, TCommon> | |
{ | |
private readonly TValue _value; | |
private readonly GradeSystem<TValue, TCommon> _gradeSystem; | |
public Grade(TValue value, GradeSystem<TValue, TCommon> system) | |
{ | |
_value = value; | |
_gradeSystem = system; | |
} | |
public TValue Value { get { return _value; } } | |
public Grade<TTarget, TCommon> To<TTarget, TTargetSystem>() where TTargetSystem : GradeSystem<TTarget, TCommon>, new() | |
{ | |
var targetSystem = new TTargetSystem(); | |
return targetSystem.FromCommon(_gradeSystem.ToCommon(_value)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment