Wednesday, January 19, 2011

Roy Osherove's String Calculator Kata - My third try with video

My third take at the Roy Osherove's String Calculator Kata. The video is on youtube here.

The class.

/// 
/// http://www.osherove.com/tdd-kata-1/
/// 
class Calculator {

    public static int Add(string numbers) {
        
        if(numbers=="") return 0;

        var delimiters = new string[1] { "," };
        delimiters     = DetermineDelimiters(ref numbers);
        numbers        = numbers.Replace("\n",delimiters[0]);
        var values     = Split(numbers, delimiters);

        return SumValues(values);        
    }

    private static int SumValues(string[] values) {
        var sum = 0;
        foreach (var v in values) {

            if (String.IsNullOrEmpty(v.Trim())) throw new ArgumentException();
            var num = int.Parse(v);
            if (num >= 1000) num = 0;
            if (num < 0) throw new ArgumentException();
            sum += num;
        }
        return sum;
    }
    private static string [] DetermineDelimiters(ref string numbers) {

        var delimiters = new string[1] { "," };

        if (numbers.StartsWith("//[")) {

            int posLF  = numbers.IndexOf("\n");
            delimiters = numbers.Substring(3, posLF - 4).Replace("]", "").Split('[');
            numbers    = numbers.Substring(posLF + 1);
        }
        else if (numbers.StartsWith("//")) {

            delimiters[0] = numbers[2].ToString();
            numbers       = numbers.Substring(4);
        }
        return delimiters;
    }
    // 2 functions to split based on a string
    // or a string array
    static string[] Split(string value, 
                          string [] splitingWords) {
 
        return value.Split(splitingWords, StringSplitOptions.None);
    }
    static string [] Split(string value, 
                           string splitingWord){
 
        return value.Split(new string[] { splitingWord }, StringSplitOptions.None);
    }    
    
}




No comments:

Post a Comment