Last active
December 17, 2015 21:49
-
-
Save nLight/5677252 to your computer and use it in GitHub Desktop.
Решение с мультиметодами и тестами.
Запустить тесты можно командой (run-tests 'schema) schema=> (run-tests 'schema) Testing schema Ran 1 tests containing 5 assertions.
0 failures, 0 errors.
{:type :summary, :pass 5, :test 1, :error 0, :fail 0}
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
(ns schema | |
(:use clojure.test)) | |
(defn- schema-type [schema data] | |
(cond | |
(and (vector? schema) (vector? (first schema))) :nested-vector | |
(vector? schema) :vector | |
(map? schema) :map | |
(keyword? schema) :keyword | |
:default (type schema))) | |
(defmulti apply-schema schema-type) | |
(defmethod apply-schema :keyword [schema data] | |
{schema (data schema)}) | |
(defmethod apply-schema :map [schema data] | |
(let [[[k v]] (seq schema)] | |
{k (apply-schema v (data k))})) | |
(defmethod apply-schema :vector [schema data] | |
(apply merge (map #(apply-schema % data) schema))) | |
(defmethod apply-schema :nested-vector [schema data] | |
(let [[schema] schema] | |
(map #(apply-schema schema %) data))) | |
(with-test | |
(def test-data { | |
:aaa "22" | |
:aaaa "New 22" | |
:bbb "434" | |
:ccc {:ddd "abc" :ddddd "Not needed" :ggg "Needed" :hard_to_believe []} | |
:zzz [ {:hhh 126 :hhhh "Don't need" :kkk "Existing key"} {:hhh "DoobyDo" :kkk "Needed" :mmm "Existing key"} ]}) | |
(def test-schema [ | |
:aaa | |
:bbb | |
:ooo | |
{:ccc [:ddd :ggg]} | |
{:zzz [[:hhh :kkk :mmm]]}]) | |
(is (= (apply-schema :a {:a "Value"}) {:a "Value"})) | |
(is (= (apply-schema [:a] {:a "Value"}) {:a "Value"})) | |
(is (= (apply-schema {:a [:b :c]} {:a {:b 1 :c 2}}) {:a {:b 1 :c 2}})) | |
(is (= (apply-schema {:a [[:b :c]]} {:a [{:b 1 :c 2} {:b 1 :c 2}]}) {:a [{:b 1 :c 2} {:b 1 :c 2}]})) | |
(is (= (apply-schema test-schema test-data) { :zzz [{:mmm nil, :kkk "Existing key", :hhh 126} {:mmm "Existing key", :kkk "Needed", :hhh "DoobyDo"}] | |
:ccc {:ggg "Needed", :ddd "abc"} | |
:ooo nil | |
:bbb "434" | |
:aaa "22"}))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Я настолько стар, что видел это еще без мультиметодов!