Skip to content

Instantly share code, notes, and snippets.

@mping-exo
Last active February 15, 2021 19:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mping-exo/9b230bc59f822a9ba58715ddb3562bc3 to your computer and use it in GitHub Desktop.
Save mping-exo/9b230bc59f822a9ba58715ddb3562bc3 to your computer and use it in GitHub Desktop.
(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