Created
August 12, 2015 20:08
-
-
Save JacobNinja/b412c12c6c28ee8fa12b to your computer and use it in GitHub Desktop.
Greeting kata solution
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
;; Core | |
(defn- maplast | |
"Apply map-fn to the last element in s | |
unless s contains only 1 element" | |
[map-fn s] | |
(if (> (count s) 1) | |
(conj (vec (butlast s)) | |
(map-fn (last s))) | |
s)) | |
(defn- uppercase? [name] | |
(= name (.toUpperCase name))) | |
(defn- strip-quotes [name] | |
(subs name 1 (dec (count name)))) | |
(defn- join-names [names] | |
(join (if (> (count names) 2) | |
", " | |
" ") | |
(maplast #(str "and " %) names))) | |
(defn- split-name [name] | |
(if (= ((juxt first last) name) | |
[\" \"]) | |
(list (strip-quotes name)) | |
(split name #"\,\s?"))) | |
(defn- greet-upcase [upcase-names] | |
(str "HELLO " | |
(.toUpperCase (join-names upcase-names)) | |
"!")) | |
(defn- greet-normal [names] | |
(str "Hello, " | |
(join-names names) | |
".")) | |
(defn greet [& names] | |
(let [split-names (mapcat split-name names) | |
upcase-names (filter uppercase? split-names) | |
normal-names (difference (into #{} split-names) | |
(into #{} upcase-names))] | |
(str (when-not (empty? normal-names) | |
(greet-normal normal-names)) | |
(when (every? not-empty [upcase-names normal-names]) | |
" AND ") | |
(when-not (empty? upcase-names) | |
(greet-upcase upcase-names))))) | |
;; Tests | |
(deftest greeting-test | |
(testing "one" | |
(is (= (greet "foo") | |
"Hello, foo."))) | |
(testing "two" | |
(is (= (greet "foo" "bar") | |
"Hello, foo and bar."))) | |
(testing "three" | |
(is (= (greet "foo" "bar" "bazz") | |
"Hello, foo, bar, and bazz."))) | |
(testing "shout" | |
(is (= (greet "FOO") | |
"HELLO FOO!"))) | |
(testing "comma" | |
(is (= (greet "foo, bar") | |
"Hello, foo and bar."))) | |
(testing "intentional comma" | |
(is (= (greet "foo" "\"bar, bazz\"") | |
"Hello, foo and bar, bazz."))) | |
(testing "shouting and normal" | |
(is (= (greet "foo" "BAR" "bazz" "\"FOO, BAR\"") | |
"Hello, foo and bazz. AND HELLO BAR AND FOO, BAR!")))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment