-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Improve metadata and docstring for (in)valid-map?
- Loading branch information
1 parent
d36aaee
commit 09e925d
Showing
1 changed file
with
25 additions
and
13 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,5 @@ | ||
(ns swark.core | ||
(:require [clojure.string :as str]) | ||
(:import [clojure.lang Named])) | ||
(:require [clojure.string :as str])) | ||
|
||
;; SWiss ARmy Knife - Your everyday clojure toolbelt! | ||
;; Copyright 2024 - Stan Verberkt ([email protected]) | ||
|
@@ -125,20 +124,33 @@ | |
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; | ||
;; Minimalistic spec | ||
|
||
|
||
(defn- check [predicate input] | ||
{::predicate predicate ::input input ::result (predicate input)}) | ||
|
||
(defn invalid-map? | ||
"Returns nil if map `input` is valid according to map `spec`. | ||
When `input` is nil, returns {::input nil}. | ||
When `input` is invalid, returns a map with a report on why it is invalid." | ||
{:added "0.1.1" | ||
:arglist '([spec input]) | ||
:doc "Returns nil if input is valid according to spec. When input is invalid, | ||
returns a map reporting how it is invalid. When input is nil, returns the | ||
special keyword ::nil. | ||
`(valid-map? {:a string?} {:a 12}) ≠> {::predicate string? ::input 12 ::result false}`" | ||
:static true} | ||
[spec input] | ||
(-> spec map? (assert "Spec should be a map!")) | ||
(assert (->> spec vals (every? ifn?)) "All vals in spec should implement IFn!") | ||
(some-> input map? (assert "Input should be a map!")) | ||
(case input | ||
nil {::input input} ; Explicit inform that input is nil | ||
(if (nil? input) | ||
::nil ; Explicit inform that input is nil | ||
(some->> input | ||
(merge-with (fn [predicate input] {::predicate predicate ::input input ::result (predicate input)}) spec) | ||
(remove (comp ::result val)) | ||
seq | ||
(into {})))) | ||
|
||
(def valid-map? (complement invalid-map?)) | ||
(merge-with check spec) | ||
(remove (comp ::result val)) | ||
seq | ||
(into {})))) | ||
|
||
(def valid-map? | ||
{:added "0.1.1" | ||
:arglist '([spec input]) | ||
:doc "Returns true if input is nil or valid according to spec." | ||
:static true} | ||
(complement invalid-map?)) |