Skip to content

Instantly share code, notes, and snippets.

@miner
Created August 31, 2012 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save miner/3554952 to your computer and use it in GitHub Desktop.
Save miner/3554952 to your computer and use it in GitHub Desktop.
sub= for @puredanger
;; inspired by https://twitter.com/puredanger/status/241282082268143619
;; reduce-kv is faster than destructuring with maps
;; use (get m k) instead of (k m) to be safe with non-keyword keys
(defn sub=
"Like = for most things, but maps compare recursively by only the keys in a, so it returns true
if a is a 'submap' of b."
[a b]
(if (and (map? a) (map? b))
(reduce-kv (fn [result k v] (and result (sub= v (get b k)))) true a)
(= a b)))
;; added non-kw keys and some deeply nested maps
(deftest test-sub=
(let [hhh (zipmap (range 1000) (range 1 1001))
hnest (zipmap (range 1000) (repeat hhh))
hnest1 (assoc hnest 1001 1002)
hnestx (assoc-in hnest [500 500] :fail)]
(are [expected left right] (= expected (sub= left right))
;; prim
true 1 1
false 1 2
;; maps
true {} {:a 1}
false {:a 1} {}
true {:a 1} {:a 1}
false {:a 1} {:a 2}
true {:a 1} {:a 1 :b 2}
;; non-kw keys
true {1 10 2 20} {1 10 2 20 3 30}
;; nested maps
true {} {:a {:b 1}}
false {:a 1} {:b {:c 2}}
true {:a {:b 1}} {:a {:b 1}}
true {:a {:b 1}} {:a {:b 1 :c 2}}
true {:a {}} {:a {:b 1}}
false {:a {:b 1}} {:a 1}
false {:a {:b 1}} {:a {:b 2}}
true {:a {:b 1}} {:a {:b 1 :c 2}}
;; deeply nested
true hnest hnest1
false hnest1 hnest
false hnestx hnest)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment