Skip to content

Instantly share code, notes, and snippets.

@brunopedroso
Created June 17, 2012 23:07
Show Gist options
  • Save brunopedroso/2946009 to your computer and use it in GitHub Desktop.
Save brunopedroso/2946009 to your computer and use it in GitHub Desktop.
ArgsKata from a Clojure newbie
(ns args_kata.core)
(def default-values {
Boolean false
String ""
Integer 0
})
(defn convert-value [type value]
(condp = type
Integer (. Integer parseInt value)
value))
(defn get-options [config args]
(if (empty? args)
{}
(let [first-token (subs (first args) 1)]
(if (= Boolean (config first-token))
(merge
{first-token true}
(get-options config (next args)) )
(merge
{first-token (convert-value (config first-token) (second args))}
(get-options config (nthnext args 2)) )
))))
(defn parser [config]
(fn [args]
(let [result (get-options config args)
missing-keys (filter #(not (result %)) (keys config))
missing-map (reduce #(merge %1 {%2 (default-values (config %2))}) {} missing-keys)]
(merge missing-map result)) ))
(ns args_kata.test.core
(:use [args_kata.core])
(:use [clojure.test])
(:use [lazytest.describe :only (describe it)]))
(describe args
(it "accepts no flags at all"
(let [parser_instance (parser {})]
(= {} (parser_instance [])) ))
(it "accepts one present flag"
(let [parser_instance (parser {"a" Boolean})]
(= {"a" true} (parser_instance ["-a"])) ))
(it "accepts one missing Boolean flag"
(let [parser_instance (parser {"a" Boolean})]
(= {"a" false} (parser_instance [])) ))
(it "accepts one present and one missing flag"
(let [parser_instance (parser {"a" Boolean "b" Boolean})]
(= {"a" true "b" false} (parser_instance ["-a"])) ))
(it "accepts two present flags"
(let [parser_instance (parser {"a" Boolean "b" Boolean})
result (parser_instance ["-a" "-b"])]
(= {"a" true "b" true} result)))
(it "accepts many present flags"
(let [parser_instance (parser {"a" Boolean "b" Boolean "c" Boolean "d" Boolean})
result (parser_instance ["-a" "-b" "-c" "-d"])]
(= {"a" true "b" true "c" true "d" true} result)))
(it "accepts one String flags"
(let [parser_instance (parser {"a" String})
result (parser_instance ["-a" "test"])]
(= {"a" "test"} result)))
(it "return empty string as the default value to strings"
(let [parser_instance (parser {"a" String})
result (parser_instance [])]
(= {"a" ""} result)))
(it "return 0 as the default value to integer"
(let [parser_instance (parser {"a" Integer})
result (parser_instance [])]
(= {"a" 0} result)))
(it "converts argument values to integer"
(let [parser_instance (parser {"a" Integer})
result (parser_instance ["-a" "1"])]
(= {"a" 1} result)))
(it "convert strings to the arg type" true)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment