Skip to content

Instantly share code, notes, and snippets.

@johnjelinek
Last active August 29, 2015 13:55
Show Gist options
  • Save johnjelinek/8774776 to your computer and use it in GitHub Desktop.
Save johnjelinek/8774776 to your computer and use it in GitHub Desktop.
(ns string-calculator
"My implementation of http://osherove.com/tdd-kata-1/"
(:use [clojure.test :only (is)])
(:require [clojure.tools.reader.edn :as edn]
[clojure.string :as string :refer [join split]]))
; CODE
(defn parse-numbers [x]
(map edn/read-string
(if-let [[_ delimiter numbers] (first (re-seq #"//(.)\n(.+)" x))]
(split numbers (re-pattern (if (or (= "." delimiter) (= "|" delimiter))
(str "\\" delimiter)
delimiter)))
(split x #",|\n"))))
(defn add [x]
(if (empty? x)
0
(let [numbers (parse-numbers x)]
(when-let [negatives (not-empty (filter neg? numbers))]
(throw (Exception. (str "negatives not allowed: " (join "," negatives)))))
(reduce + numbers))))
; TEST
(is (= 0 (add ""))
"Add \"\" should be 0")
(is (= 1 (add "1"))
"Add \"1\" should be 1")
(is (= 3 (add "1,2"))
"Add \"1,2\" should be 3")
(is (= (+ 1 2 3 4 5 6 7) (add "1,2,3,4,5,6,7"))
"Add \"1,2,3,4,5,6,7\" should be its sum")
(is (= 6 (add "1\n2,3"))
"Add \"1\n2,3\" should be 6")
(is (= 3 (add "//;\n1;2"))
"Add \"//;\n1;2\" should be 3")
(is (= 3( add "//.\n1.2"))
"Add \"//.\n1.2\" should be 3")
(is (= 3( add "//|\n1|2"))
"Add \"//|\n1|2\" should be 3")
(is (thrown? Exception (add "-1"))
"Add \"-1\" should be \"negatives not allowed: -1")
(is (thrown? Exception (add "-1,-2,3,-4"))
"Add \"-1,-2,3,-4\" should be \"negatives not allowed: -1,-2,-4")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment