Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add =? #13

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
30 changes: 30 additions & 0 deletions src/flatland/useful/fn.clj
Original file line number Diff line number Diff line change
Expand Up @@ -169,3 +169,33 @@
(if (= args (get cache :args ::not-found))
cache
{:args args, :value (apply f args)})))))))

(defprotocol EquivChecker
"Given an object, produce a function for quickly testing equality with that object."
(=? [x] "Return a function of y which computes (= x y)."))

(let [identity-checker {:=? (fn [x]
(fn [y]
(identical? x y)))}
equals-checker {:=? (fn [^Object x]
(fn [^Object y]
(.equals x y)))}]
(extend nil
EquivChecker identity-checker)
(extend clojure.lang.Keyword
EquivChecker identity-checker)
(extend clojure.lang.Symbol
EquivChecker equals-checker)
(extend String
EquivChecker equals-checker))

(extend-protocol EquivChecker
Number
(=? [x]
(fn [y]
(and (instance? Number y)
(clojure.lang.Numbers/equal x y))))
Object
(=? [x]
(fn [y]
(= x y))))
10 changes: 10 additions & 0 deletions test/flatland/useful/fn_test.clj
Original file line number Diff line number Diff line change
Expand Up @@ -79,3 +79,13 @@

(deftest test-ignoring-nils
(is (= 6 ((ignoring-nils +) 1 nil 2 nil nil 3))))

(deftest test-=?
(let [objs [1 :x [2] "foo"]]
(doseq [i (range (count objs))
:let [x (objs i)
f (=? x)]
j (range (count objs))
:let [y (objs j)]]
(is (= (boolean (f y))
(boolean (= i j)))))))