How to check distinct id in spec/coll-of

泪湿孤枕 提交于 2019-12-08 02:29:21

问题


(s/def ::users (s/coll-of ::user :distinct true))

The spec above requires each user map to be distinct but How can I specify it to check for distinct :user/ids only

The collection bellow shouldn't be allowed:

[{:id 10 :name "Jessica"} {:id 10 :name "Erica"}]

回答1:


(s/def ::id (s/int-in 0 40)) ; just for testing purposes
(s/def ::name string?)
(s/def ::user (s/and (s/keys :req-un [::id ::name])))
(s/def ::user-list (s/and
                       (s/coll-of ::user :distinct true :into [])
                       #(if (empty? %) true (apply distinct? (mapv :id %)))))

(deftest so-test
    (let [users [{:id 11 :name "Jessica"} {:id 11 :name "Erica"}]]
        (prn (g/generate (s/gen ::user-list)))
        (s/assert ::user-list users)))


来源:https://stackoverflow.com/questions/46135111/how-to-check-distinct-id-in-spec-coll-of

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!