Skip to content

Instantly share code, notes, and snippets.

@Vinai
Created September 22, 2017 09:00
Show Gist options
  • Save Vinai/ca004731d8e1fb385bc238d997cdc3d3 to your computer and use it in GitHub Desktop.
Save Vinai/ca004731d8e1fb385bc238d997cdc3d3 to your computer and use it in GitHub Desktop.
String calculator kata in Clojure done early while learning the language.
(ns string-calculator.core
(:require [clojure.string :refer [join]]))
(defn numbers-from-string
[string]
(map #(Integer. %) (re-seq #"-?\d+" string)))
(defn add
[string]
(if (empty? string) 0
(let [numbers (numbers-from-string string)
negatives (filter #(< % 0) numbers)]
(if (not (empty? negatives))
(throw (Exception. (str "Negative numbers are not allowed: "
(join ", " negatives))))
(reduce + (filter #(<= % 1000) numbers))))))
(defn a [s]
(if (= "" s) 0
(let [n (map #(Integer. %) (re-seq #"-?\d+" s)) n- (filter #(< % 0) n)]
(if (< 0 (count n-)) (throw (Exception. (str "Negative numbers are not allowed: " (join ", " n-))))
(reduce + (filter #(<= % 1000) n))))))
(ns string-calculator.core-test
(:require [clojure.test :refer :all]
[string-calculator.core :refer :all]))
(deftest string-calculator
(testing "adding an empty string"
(is (= 0 (add ""))))
(testing "adding one number"
(is (= 2 (add "2"))))
(testing "adding two numbers"
(is (= 3 (add "1,2"))))
(testing "adding numbers separated by newline"
(is (= 6 (add "1\n2,3"))))
(testing "adding numbers separated by custom delimiter"
(is (= 3 (add "//[;]\n1;2"))))
(testing "adding negative numbers throws exception with negatives"
(is (thrown-with-msg? Exception #"Negative numbers are not allowed: -3, -1"
(add "2,-3,2,-1"))))
(testing "adding numbers separated by multi-character delimiter"
(is (= 3 (add "//[***]\n1***2"))))
(testing "numbers larger than 1000 are ignored"
(is (= 1001 (add "1,1000,1001"))))
(testing "adding numbers separated by multiple delimiters"
(is (= 6 (add "//[;;][&/]\n1;;2&/3")))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment