Order-preserving-set

This commit is contained in:
Simon Brooke 2018-09-30 14:38:57 +01:00
parent ab44e355f6
commit 3baa7c12a5
3 changed files with 25 additions and 9 deletions

View file

@ -46,10 +46,10 @@
;; TODO: candidate for moving to adl-support.core ;; TODO: candidate for moving to adl-support.core
[form request] [form request]
`(if-valid-user `(if-valid-user
~form ~form
~request ~request
{:status 403 {:status 403
:body (json/write-str "You must be logged in to do that")})) :body (json/write-str "You must be logged in to do that")}))
(defmacro with-params-or-error (defmacro with-params-or-error
@ -64,9 +64,6 @@
:body (json/write-str (str "The following params are required: " ~required))})) :body (json/write-str (str "The following params are required: " ~required))}))
;; (with-params-or-error (/ 1 0) {:a 1 :b 2} #{:a :b :c})
;; (with-params-or-error "hello" {:a 1 :b 2} #{:a :b })
(defmacro do-or-server-fail (defmacro do-or-server-fail
"Evaluate this `form`; if it succeeds, return an HTTP response with this "Evaluate this `form`; if it succeeds, return an HTTP response with this
status code and the JSON-formatted result as body; if it fails, return an status code and the JSON-formatted result as body; if it fails, return an
@ -78,6 +75,5 @@
{:status ~status {:status ~status
:body (:result r#)} :body (:result r#)}
{:status 500 {:status 500
:body r#}))) :body r#})))

View file

@ -658,3 +658,17 @@
0 0
(expt 10 v))) (expt 10 v)))
(catch Exception _ 0))) (catch Exception _ 0)))
(defn order-preserving-set
"The Clojure `set` function does not preserve the order in which elements are
passed to it. This function is like `set`, except
1. It returns a list, not a hashset, and
2. It is order-preserving."
[collection]
(loop [lhs (list (first collection))
rhs (rest collection)]
(cond
(empty? rhs) (reverse lhs)
(some #(= (first rhs) %) lhs) (recur lhs (rest rhs))
true (recur (cons (first rhs) lhs) (rest rhs)))))

View file

@ -598,3 +598,9 @@
(is (= (key-names e2) #{"id" "shard"})) (is (= (key-names e2) #{"id" "shard"}))
(is (= (key-names e2 true) #{:id :shard}))))) (is (= (key-names e2 true) #{:id :shard})))))
(deftest order-preserving-set-tests
(testing "order-preserving-set"
(is (= '(:a) (order-preserving-set '(:a :a :a :a))))
(is (= '(:a) (order-preserving-set [:a :a :a :a])))
(is (= '(:a :b :c :d :e) (order-preserving-set '(:a :a :b :c :a :b :d :c :e))))))