Last active
February 3, 2024 21:03
-
-
Save wdhowe/85fe508ee944e3dc272b644e6d4fb4aa to your computer and use it in GitHub Desktop.
Clojure Errors/Success collection checking
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
;; These protocols are also available in: https://github.com/wdhowe/clj-contrib | |
(defprotocol Errors | |
"A protocol for finding errors in a collection." | |
(errors [coll] "Returns a map of the `:counts/errors`, which are entries with `:error` keys.")) | |
(extend-protocol Errors | |
clojure.lang.Sequential | |
(errors | |
[coll] | |
(->> (filter #(contains? % :error) coll) | |
(count) | |
(hash-map :counts/errors))) | |
clojure.lang.IPersistentMap | |
(errors | |
[coll] | |
(if (contains? coll :error) | |
{:counts/errors 1} | |
{:counts/errors 0})) | |
nil | |
(errors [_] {:counts/errors 0})) | |
(comment | |
(errors []) | |
(errors [{:error "foo"}, {:error "foo"}]) | |
(errors [{:error "foo"}, {:success "foo"}]) | |
(errors [{:success "foo"}, {:success "foo"}]) | |
(errors {}) | |
(errors {:success "foo"}) | |
(errors {:error "foo"}) | |
(errors nil)) | |
(defprotocol Success | |
"A protocol for finding success/non errors in a collection." | |
(success [coll] "Count all non errors as success. | |
Returns a map of the `:counts/success`, which are entries without ':error' keys.")) | |
(extend-protocol Success | |
clojure.lang.Sequential | |
(success | |
[coll] | |
(->> (remove #(contains? % :error) coll) | |
(count) | |
(hash-map :counts/success))) | |
clojure.lang.IPersistentMap | |
(success | |
[coll] | |
(if (and (not (contains? coll :error)) (not-empty coll)) | |
{:counts/success 1} | |
{:counts/success 0})) | |
nil | |
(success [_] {:counts/success 0})) | |
(comment | |
(success []) | |
(success [{:error "foo"}, {:error "foo"}]) | |
(success [{:error "foo"}, {:success "foo"}]) | |
(success [{:success "foo"}, {:success "foo"}]) | |
(success {}) | |
(success {:success "foo"}) | |
(success {:error "foo"}) | |
(success nil)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment