Skip to content

Commit

Permalink
Implement and test filter-keys and select-namespaced
Browse files Browse the repository at this point in the history
  • Loading branch information
verberktstan committed Jan 24, 2024
1 parent 1907c13 commit 754d4d5
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
27 changes: 26 additions & 1 deletion src/swark/core.cljc
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
(ns swark.core
(:require [clojure.string :as str]))
(:require [clojure.string :as str])
(:import [clojure.lang Named]))

;; SWiss ARmy Knife - Your everyday clojure toolbelt!
;; Copyright 2024 - Stan Verberkt ([email protected])
Expand Down Expand Up @@ -32,6 +33,30 @@
(map (juxt key (comp f val)))
(into {}))))

(defn filter-keys
[map pred]
{:added "0.1.3"
:arglists '([map pred])
:doc "Returns a map containing only those entries in map whose key return logical true on evaluation of (pred key)."
:static true}
(cond->> map
pred (filter (comp pred key))
map seq
:always (into {})))

(defn select-namespaced
{:added "0.1.3"
:arglist '([map] [map ns])
:doc "Returns a map containing only those entries in map whose keys' namespace match ns. When ns is nil, returns a map containing only non-namespaced keys."
:static true}
([map]
(select-namespaced map nil))
([map ns]
(-> map map? assert)
(when-not (string? ns) (some->> ns (instance? Named) assert))
(let [predicate (if ns #{(name ns)} nil?)]
(filter-keys map (comp predicate namespace)))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Regarding strings

Expand Down
17 changes: 17 additions & 0 deletions test/swark/core_test.clj
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,23 @@
(t/is (thrown? AssertionError (sut/map-vals nil m)))
(t/is (nil? (sut/map-vals inc nil)))))

(t/deftest filter-keys
(let [map {:user-id 1 :user/name "Username" ::test "Testdata"}
ns-str (namespace ::this)]
(t/are [result f] (= result (sut/filter-keys map f))
{:user-id 1} (complement namespace)
{:user/name "Username"} (comp #{"user"} namespace)
{::test "Testdata"} (comp #{ns-str} namespace)
{} (comp #{"unknown"} namespace))))

(t/deftest select-namespaced
(let [map {:user-id 1 :user/name "Username" ::test "Testdata"}]
(t/are [result ns] (= result (sut/select-namespaced map ns))
{:user-id 1} nil
{:user/name "Username"} "user"
{::test "Testdata"} (namespace ::this)
{} "unknown")))

(t/deftest ->str
(t/are [result input] (= result (sut/->str input))
"Hello, Swark!" "Hello, Swark!"
Expand Down

0 comments on commit 754d4d5

Please sign in to comment.