Skip to content

Instantly share code, notes, and snippets.

@uwo
Last active January 30, 2019 23:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uwo/74d48ba6b3c4cbd92111abc8212e3b24 to your computer and use it in GitHub Desktop.
Save uwo/74d48ba6b3c4cbd92111abc8212e3b24 to your computer and use it in GitHub Desktop.
Search trees like ctrl-F ?
.cpcache
.nrepl-port

deps.edn

{:deps {fix/me {:git/url "" :sha ""}}}
{:paths ["."]
:deps {gist-uwo/osxclip {:git/url "https://gist.github.com/uwo/23b7a81fd97818368400bb7c02086562"
:sha "ceee392df6d3f7607bd5e80f0eb80aafcdcda348"}}}
(ns tsearch
(:require [clojure.zip :as z]
[osxclip :refer [pbslurpe pbslurp]]))
(defn zip
"Zip the given clojure data. Assumes a shape, like what would be
returned from a d/pull"
;; mostly taken from https://clojuredocs.org/clojure.zip/zipper#example-5845617fe4b0782b632278d3
[root]
(letfn [(branch? [x]
(or (map? x)
(sequential? x)
(set? x)))
(make-node [p xs]
(if (map-entry? p)
(vec xs)
(into (empty p) xs)))]
(z/zipper branch? seq make-node root)))
(defn searchable?
"Does text search make sense against the string representation of the
given value?"
[x]
((some-fn number? string? keyword?) x))
(defn tsearch
#_(test #'tsearch)
"Goal: Search a tree like ctrl-F in a browser :)"
{:test (fn []
;; search edn in paste buffer
(clojure.pprint/pprint (tsearch (pbslurpe) "text")))}
[tree text]
(let [z (zip tree)
re (re-pattern text)
match? #(when (searchable? %)
(re-find re (str %)))]
(loop [loc z results []]
(if (z/end? loc)
results
(let [loc (z/next loc)
node (z/node loc)
result (when (map-entry? node)
(let [[k v] node]
(when (or (match? k) (match? v))
node #_{:node node})))]
(recur loc (if result (conj results result) results)))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment