Created
July 29, 2013 18:40
-
-
Save maio/6106595 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
(ns kata.core-test | |
(:use clojure.test) | |
(:require [clojure.string :as str])) | |
(def default-delimiter ",|\n") | |
(defn parse-delimiter [s] | |
(if-let [[_ delimiter x] (first (re-seq #"//(.)\n(.*)" s))] | |
[(re-pattern delimiter) x] | |
[(re-pattern default-delimiter) s])) | |
(defn parse-numbers [s delimiter-re] | |
(map read-string (str/split s delimiter-re))) | |
(defn build-negatives-exception [negatives] | |
(Exception. (str "Unexpected negative numbers: " (str/join ", " negatives)))) | |
(defn add [s] | |
(if (empty? s) | |
0 | |
(let [[delimiter-re s] (parse-delimiter s) | |
numbers (parse-numbers s delimiter-re)] | |
(if-let [negatives (not-empty (filter neg? numbers))] | |
(throw (build-negatives-exception negatives))) | |
(reduce + numbers)))) | |
(deftest string-calculator | |
(testing "it returns 0 for empty input" | |
(is (= (add "") 0))) | |
(testing "it returns given number for single number input" | |
(is (= (add "1") 1)) | |
(is (= (add "11") 11))) | |
(testing "it returns sum of comma delimited numbers" | |
(is (= (add "1,1") 2))) | |
(testing "it treats newline as delimiter" | |
(is (= (add "1\n1") 2))) | |
(testing "it supports custom delimiter" | |
(is (= (add "//;\n1;1") 2))) | |
(testing "when input contains some negative numbers" | |
(testing "it throws exception" | |
(is (thrown? Exception (add "-1")))) | |
(testing "thrown exception contains list of all negative numbers" | |
(is (thrown-with-msg? Exception #"Unexpected negative numbers: -1" (add "-1"))) | |
(is (thrown-with-msg? Exception #"Unexpected negative numbers: -1, -2" (add "0,-1,-2")))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment