Skip to content

Instantly share code, notes, and snippets.

@cljforge
cljforge / clojure group ips
Created December 22, 2015 10:50
Raw method of grouping IP addresses. Desctructive operation.
(defn group-ips [ips]
(if (> (count ips) 1)
(let [ips (->> ips distinct sort-ips)
to-array (fn [ip-str] (str/split ip-str #"\."))]
(reduce
(fn [acc el]
(condp #(re-matches %1 %2) (last acc)
#"^$" [el]
#"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"
(let [arr-l (map parse-int (to-array (last acc)))
(defn sort-ips [ips]
(sort (fn [left right]
(let [left (read-string (str/replace left #"\." ""))
right (read-string (str/replace right #"\." ""))]
(< left right)))
ips))
@cljforge
cljforge / clojure distinct by
Created December 22, 2015 10:48
Returns a lazy sequence of the elements of coll, removing any elements that return duplicate values when passed to a function f
(defn distinct-by
"Returns a lazy sequence of the elements of coll, removing any elements that
return duplicate values when passed to a function f."
[f coll]
(let [step (fn step [xs seen]
(lazy-seq
((fn [[x :as xs] seen]
(when-let [s (seq xs)]
(let [fx (f x)]
(if (contains? seen fx)
@cljforge
cljforge / clojure string to pattern
Created December 22, 2015 10:47
Clojure code to escape regExp characters from string
(def regex-char-esc-smap
(let [esc-chars "()&^%$#!?*."]
(zipmap esc-chars
(map #(str "\\" %) esc-chars))))
(defn str-to-pattern
[string]
(->> string
(replace regex-char-esc-smap)
(reduce str)