Skip to content

Commit

Permalink
Extend unid to support filter regex and omit dashes
Browse files Browse the repository at this point in the history
  • Loading branch information
verberktstan committed Feb 28, 2024
1 parent c9f30da commit 270124f
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
11 changes: 9 additions & 2 deletions src/swark/core.cljc
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
(ns swark.core
(:require [clojure.core.async :as a]
[clojure.edn :as edn]
[clojure.string :as str]))

;; SWiss ARmy Knife - Your everyday clojure toolbelt!
Expand Down Expand Up @@ -123,15 +124,21 @@
([] (-> (random-uuid) str))
([existing]
(unid nil existing))
([{:keys [min-length] :or {min-length 1}} existing]
([{:keys [min-length filter-regex no-dashes?] :or {min-length 1}} existing]
(-> existing set? assert)
(reduce
(fn [s char]
(if (and s (>= (count s) min-length) (-> s existing not) (-> s reverse first #{"-"} not))
(reduced s)
(str s char)))
nil
(seq (unid)))))
(cond->> (seq (unid))
no-dashes? (remove #{\-})
filter-regex (filter (comp (partial re-find filter-regex) str))))))

(comment
(unid {:filter-regex #"\d" :min-length 13} #{})
(re-find #"\d" (str \a)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Regarding keywords
Expand Down
14 changes: 12 additions & 2 deletions test/swark/core_test.clj
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
(ns swark.core-test
(:require [clojure.test :as t]
(:require [clojure.edn :as edn]
[clojure.test :as t]
[swark.core :as sut]))

(t/deftest key-by
Expand Down Expand Up @@ -70,7 +71,16 @@
(t/is (-> #{"x"} sut/unid count #{1}))
(t/is (->> #{"xyzab"} (sut/unid {:min-length 5}) count (>= 5)))
(t/is (-> (reduce (fn [x _] (conj x (sut/unid x))) #{} (range 999)) count #{999}))
(t/is (-> (reduce (fn [x _] (conj x (sut/unid {:min-length 4} x))) #{} (range 999)) count #{999})))
(t/is (-> (reduce (fn [x _] (conj x (sut/unid {:min-length 4} x))) #{} (range 999)) count #{999}))
(let [three-digits (sut/unid {:min-length 3 :no-dashes? true :filter-regex #"\d"} #{})
four-letters (sut/unid {:min-length 4 :no-dashes? true :filter-regex #"\D"} #{})
five-chars (sut/unid {:min-length 5} #{})]
(t/is (-> three-digits count #{3}))
(t/is (->> three-digits seq (every? (comp number? edn/read-string str))))
(t/is (-> four-letters count #{4}))
(t/is (->> four-letters seq (every? (comp (partial re-find #"\D") str))))
(t/is (-> five-chars count #{5}))
(t/is (->> five-chars seq (every? (comp (partial re-find #"[a-z]|[0-9]|\-") str))))))

(t/deftest ->keyword
(t/are [result args] (= result (apply sut/->keyword args))
Expand Down

0 comments on commit 270124f

Please sign in to comment.