Created
February 15, 2021 19:19
-
-
Save mping/c70a29c66a45c973e70cc97193ff9c40 to your computer and use it in GitHub Desktop.
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
(require '[clojure.spec.alpha :as s]) | |
(s/def ::test (s/and (s/keys :req-un [(or ::key1 ::key2)]) | |
(fn [{:keys [key1 key2]}] | |
(not (and key1 key2))))) | |
;; s/or validates some of the keys | |
;; the (fn..) ensures that both keys CANNOT be present | |
user=> user=> (s/explain ::test {:key1 1 :key2 2 }) | |
{:key1 1, :key2 2} - failed: (fn [{:keys [key1 key2]}] (not (and key1 key2))) spec: :user/test | |
nil | |
user=> (s/explain ::test {}) | |
{} - failed: (or (contains? % :key1) (contains? % :key2)) spec: :user/test | |
nil | |
user=> | |
user=> (s/explain ::test {:key1 1 }) | |
Success! | |
nil | |
user=> (s/explain ::test {:key2 2}) | |
Success! | |
nil | |
;; CAVEAT: nils are allowed | |
user=> (s/explain ::test {:key1 nil :key2 2}) | |
Success! | |
nil | |
;; for NIL handling, the anonymous function should check if the keys are NOT present, not their value | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment