Skip to content

Instantly share code, notes, and snippets.

@nLight
Last active December 17, 2015 21:49
Show Gist options
  • Save nLight/5677252 to your computer and use it in GitHub Desktop.
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}
(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"})))
@svenyurgensson
Copy link

Она ж неправильно выдает результат :ooo должен быть nil и :mmm = nil должен быть в ключе :zzz
А так все круто!

{:zzz
({:kkk "Existing key", :hhh 126}
{:mmm "Existing key", :kkk "Needed", :hhh "DoobyDo"}),
:ccc {:ggg "Needed", :ddd "abc"},
:bbb "434",
:aaa "22"}

@MaksimenkoPG
Copy link

Отсыпьте, посоны!

@nLight
Copy link
Author

nLight commented May 30, 2013

Вернул nil на место :)

@temochka
Copy link

да это какой-то C++ посоны :)

@nLight
Copy link
Author

nLight commented May 31, 2013

Ни разу не программировал на Си++

@svenyurgensson
Copy link

Я настолько стар, что видел это еще без мультиметодов!

@Suor
Copy link

Suor commented Jun 2, 2013

нахуй такоё размазывание логики

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment