Skip to content

Instantly share code, notes, and snippets.

@rarous
Created December 9, 2014 06:07
Show Gist options
  • Save rarous/c03e9fc7059d34860f3d to your computer and use it in GitHub Desktop.
Save rarous/c03e9fc7059d34860f3d to your computer and use it in GitHub Desktop.
(use 'speclj.core)
(require '[clojure.string :as str])
(defn- assert-positives [^String s]
(if-let [neg (re-seq #"-\d+" s)]
(throw (Exception. (str "Unexpected negative numbers: " (str/join ", " neg))))))
(defn- parse-input [^String s]
(if-let [[[_ sep text]] (re-seq #"//(.+)\n(.+)" s)]
[text sep]
[(if (empty? s) "0" s) ",|\n"]))
(defn calc [^String s]
(assert-positives s)
(let [[text sep] (parse-input s)
nums (str/split text (re-pattern sep))]
(transduce (map read-string) + nums)))
(describe "String calculator"
(context "given empty string on input"
(it "should return zero"
(should= 0 (calc ""))))
(context "given single number on input"
(it "should return that number"
(should= 1 (calc "1"))
(should= 2 (calc "2"))))
(context "given numbers separated by comma"
(it "should return sum of the numbers"
(should= 2 (calc "1,1"))
(should= 3 (calc "1,1,1"))))
(context "given numbers separated by new line"
(it "should return sum of the numbers"
(should= 2 (calc "1\n1"))))
(context "given separator and numbers separated by that separator"
(it "should return sum of the numbers"
(should= 2 (calc "//;\n1;1")))))
(context "given negative numbers"
(it "should throw"
(should-throw (calc "-1")))
(it "should throw with negative numbers in message"
(should-throw Exception "Unexpected negative numbers: -1, -2" (calc "-1,1,-2"))))
(run-specs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment