Some tools I use often, w/o any external deps.
Some tools I use often, w/o any external deps.
(->?singleton coll)(->vec x)(abs n)(ajax-lite uri
{:keys [method params headers timeout-ms resp-type with-credentials?
progress-fn errorf]
:as opts
:or {method :get timeout-ms 10000 resp-type :auto errorf logf}}
callback)Alpha - subject to change. Simple+lightweight Ajax via Google Closure. Returns nil, or the xhr instance. Ref. https://developers.google.com/closure/library/docs/xhrio.
(ajax-lite "/my-post-route" {:method :post :params {:username "Rich Hickey" :type "Awesome"} :headers {"Foo" "Bar"} :resp-type :text :timeout-ms 7000 :with-credentials? false ; Enable if using CORS (requires xhr v2+) } (fn async-callback [resp-map] (let [{:keys [success? ?status ?error ?content ?content-type]} resp-map] ;; ?status - 200, 404, ..., or nil on no response ;; ?error - e/o #{:xhr-pool-depleted :exception :http-error :abort ;; :timeout :no-content <http-error-status> nil} (js/alert (str "Ajax response: " resp-map)))))
Alpha - subject to change.
Simple+lightweight Ajax via Google Closure. Returns nil, or the xhr instance.
Ref. https://developers.google.com/closure/library/docs/xhrio.
(ajax-lite "/my-post-route"
{:method :post
:params {:username "Rich Hickey"
:type "Awesome"}
:headers {"Foo" "Bar"}
:resp-type :text
:timeout-ms 7000
:with-credentials? false ; Enable if using CORS (requires xhr v2+)
}
(fn async-callback [resp-map]
(let [{:keys [success? ?status ?error ?content ?content-type]} resp-map]
;; ?status - 200, 404, ..., or nil on no response
;; ?error - e/o #{:xhr-pool-depleted :exception :http-error :abort
;; :timeout :no-content <http-error-status> nil}
(js/alert (str "Ajax response: " resp-map)))))(as-?bool x)(as-?float x)(as-?int x)(as-?kw x)(as-?name x)(as-?nblank x)(as-bool x)(as-float x)(as-int x)(as-map kvs & [kf vf])Cross between hash-map & map-kvs.
Cross between `hash-map` & `map-kvs`.
(assert-min-encore-version min-version)(assertion-error msg)(assoc-some m & kvs)Assocs each kv iff its value is not nil.
Assocs each kv iff its value is not nil.
(assoc-when m & kvs)Assocs each kv iff its val is truthy.
Assocs each kv iff its val is truthy.
(atom? x)(backport-run! proc coll)run! from Clojure 1.7+
`run!` from Clojure 1.7+
(bench nlaps bench*-opts & body)(case-eval e & clauses)Like case but evaluates test constants for their compile-time value.
Like `case` but evaluates test constants for their compile-time value.
(catch-errors & body)Experimental. Returns [<?result> <?error>].
Experimental. Returns [<?result> <?error>].
(caught-error-data & body)Handy for error-throwing unit tests.
Handy for error-throwing unit tests.
(chan? x)(check-all test)(check-all test & more)Experimental. Returns all logical false/throwing expressions (ids/forms), or nil.
Experimental. Returns all logical false/throwing expressions (ids/forms), or nil.
(check-some test)(check-some test & more)Experimental. Returns first logical false/throwing expression (id/form), or nil.
Experimental. Returns first logical false/throwing expression (id/form), or nil.
(clamp nmin nmax n)(clamp* nmin nmax n)(clj1098 x)Workaround for Clojure versions [1.4, 1.5) that blow up on reduce-kvs
against a nil coll, Ref. http://dev.clojure.org/jira/browse/CLJ-1098.
Workaround for Clojure versions [1.4, 1.5) that blow up on `reduce-kv`s against a nil coll, Ref. http://dev.clojure.org/jira/browse/CLJ-1098.
(compile-if test then & [?else])Evaluates test. If it doesn't error and returns logical true, expands to
then, otherwise expands to else. Stolen from clojure.core.reducers.
(compile-if (Class/forName "java.util.concurrent.ForkJoinTask")
(do-cool-stuff-with-fork-join)
(fall-back-to-executor-services))
Evaluates `test`. If it doesn't error and returns logical true, expands to `then`, otherwise expands to `else`. Stolen from `clojure.core.reducers`. (compile-if (Class/forName "java.util.concurrent.ForkJoinTask") (do-cool-stuff-with-fork-join) (fall-back-to-executor-services))
(cond! & clauses)Like cond but throws on no-match like case, condp.
Like `cond` but throws on no-match like `case`, `condp`.
(cond-throw & args)(conj-some coll ?x)(conj-some coll ?x & ?xs)(contains-in? coll ks)(count-words s)(debugf fmt & xs)(declare-remote & names)Declares the given ns-qualified names, preserving symbol metadata. Useful for circular dependencies.
Declares the given ns-qualified names, preserving symbol metadata. Useful for circular dependencies.
(defalias target)(defalias name target)(defalias name target doc)Defines an alias for a var, preserving metadata. Adapted from clojure.contrib/def.clj, Ref. http://goo.gl/xpjeH
Defines an alias for a var, preserving metadata. Adapted from clojure.contrib/def.clj, Ref. http://goo.gl/xpjeH
(defonce* name expr)Like clojure.core/defonce but supports optional docstring and attributes
map for name symbol.
Like `clojure.core/defonce` but supports optional docstring and attributes map for name symbol.
(dissoc-in m ks & dissoc-ks)(distinct-by keyfn coll)Like sort-by for distinct. Based on clojure.core/distinct.
Like `sort-by` for distinct. Based on clojure.core/distinct.
(distinct-elements? x)(distinctv coll)(distinctv keyfn coll)Prefer set when order doesn't matter (much faster).
Prefer `set` when order doesn't matter (much faster).
(doto-cond [name x] & clauses)Diabolical cross between doto, cond-> and as->.
Diabolical cross between `doto`, `cond->` and `as->`.
Used for lib-consumer version assertions
Used for lib-consumer version assertions
(error-data x)Returns data map iff x is an error of any type on platform.
Returns data map iff `x` is an error of any type on platform.
(error? x)(errorf fmt & xs)(exp-backoff nattempt
&
[{:keys [factor] min' :min max' :max :or {factor 1000}}])Returns binary exponential backoff value.
Returns binary exponential backoff value.
(explode-keyword k)(fatalf fmt & xs)(filter-keys pred m)(filter-kvs predk predv m)(filter-vals pred m)(format fmt & args)Like clojure.core/format but:
format!).Like `clojure.core/format` but: * Returns "" when fmt is nil rather than throwing an NPE. * Formats nil as "nil" rather than "null". * Provides ClojureScript support via goog.string.format (this has fewer formatting options than Clojure's `format`!).
(format* fmt args)(format-query-string m)(fq-name x)Like name but fully qualified: includes namespace in string when present.
Like `name` but fully qualified: includes namespace in string when present.
(fzipmap ks vs)Faster zipmap using transients.
Faster `zipmap` using transients.
(gc-now?)(get-window-location)Returns browser window's current location. Forgeable.
Returns browser window's current location. Forgeable.
(greatest coll & [?comparator])Returns the 'greatest' element in coll in O(n) time.
Returns the 'greatest' element in coll in O(n) time.
(have (:!) x)(have (:!) pred (:in) x)(have (:!) pred (:in) x & more-xs)EXPERIMENTAL. Takes a pred and one or more xs. Tests pred against each x, trapping errors. If any pred test fails, throws a detailed error. Otherwise returns input x/xs for convenient inline-use/binding.
Options:
AssertionErrors subject to *assert* value (useful
for catching errors during dev). Use a :! first arg to instead throw
RuntimeExceptions irrespective of *assert* value (useful for important
conditions in production).:in arg after pred to treat x/xs as evaluated coll/colls.hpred for various convenient pred modifier forms.Provides a small, simple, deeply flexible alternative to heavier tools like core.typed, Prismatic/schema.
(fn square [x] (let [x (have integer? x)] (* x x))) (fn mult [x y] (let [[x y] (have integer? x y)] (* x y))) (fn mult-many [& xs] (reduce * (have :! [:or integer? float?] :in xs)))
EXPERIMENTAL. Takes a pred and one or more xs. Tests pred against each x,
trapping errors. If any pred test fails, throws a detailed error. Otherwise
returns input x/xs for convenient inline-use/binding.
Options:
* By default throws `AssertionError`s subject to `*assert*` value (useful
for catching errors during dev). Use a `:!` first arg to instead throw
`RuntimeException`s irrespective of `*assert*` value (useful for important
conditions in production).
* Use an `:in` arg after pred to treat x/xs as evaluated coll/colls.
* See `hpred` for various convenient pred modifier forms.
Provides a small, simple, deeply flexible alternative to heavier tools like
core.typed, Prismatic/schema.
(fn square [x] (let [x (have integer? x)] (* x x)))
(fn mult [x y] (let [[x y] (have integer? x y)] (* x y)))
(fn mult-many [& xs] (reduce * (have :! [:or integer? float?] :in xs)))(have! & args)(have!? & args)(have-in a1 & an)(have-in! & args)(have? (:!) x)(have? (:!) pred (:in) x)(have? (:!) pred (:in) x & more-xs)EXPERIMENTAL. Like have but returns true rather than input on success
(convenient for use in :pre/:post conds).
NB Be cautious using :! tests in :pre/:post conds since :pre/:post conds
are themselves subject to *assert* val.
(fn square [x] {:pre [(have? integer? x)]} (* x x)) (fn mult [x y] {:pre [(have? integer? x y)]} (* x y))
EXPERIMENTAL. Like `have` but returns true rather than input on success
(convenient for use in :pre/:post conds).
**NB** Be cautious using `:!` tests in :pre/:post conds since :pre/:post conds
are themselves subject to `*assert*` val.
(fn square [x] {:pre [(have? integer? x)]} (* x x))
(fn mult [x y] {:pre [(have? integer? x y)]} (* x y))(hcond hard? ns-str line x_ x-form pred pred-form)Implementation detail.
Implementation detail.
(hthrow hard? ns-str ?line form val & [?err])Implementation detail.
Implementation detail.
(if-cljs then else)Executes then clause iff generating ClojureScript code.
Useful for writing macros that can produce different Clj/Cljs code (this isn't
something Cljx currently provides support for). Stolen from Prismatic code,
Ref. http://goo.gl/DhhhSN, http://goo.gl/Bhdyna.
Executes `then` clause iff generating ClojureScript code. Useful for writing macros that can produce different Clj/Cljs code (this isn't something Cljx currently provides support for). Stolen from Prismatic code, Ref. http://goo.gl/DhhhSN, http://goo.gl/Bhdyna.
(if-lets bindings then)(if-lets bindings then else)Like if-let but binds multiple values iff all tests are true.
Like `if-let` but binds multiple values iff all tests are true.
(infof fmt & xs)(interleave-all)(interleave-all c1)(interleave-all c1 c2)(interleave-all c1 c2 & colls)Greedy version of interleave, Ref. http://goo.gl/KvzqWb.
Greedy version of `interleave`, Ref. http://goo.gl/KvzqWb.
(into-all to from)(into-all to from & more)Like into but supports multiple "from"s.
Like `into` but supports multiple "from"s.
(join-once separator & coll)Like clojure.string/join but ensures no double separators.
Like `clojure.string/join` but ensures no double separators.
(keys<= m ks)(keys= m ks)(keys=nnil? m ks)(keys>= m ks)(keywordize-map m)(ks-nnil? ks m)(ks<= ks m)(ks= ks m)(ks>= ks m)(least coll & [?comparator])Returns the 'least' element in coll in O(n) time.
Returns the 'least' element in coll in O(n) time.
(log & xs)(logf fmt & xs)(logp & xs)(map-keys f m)(map-kvs kf vf m)(map-vals f m)(mapply f & args)Like apply but assumes last arg is a map whose elements should be applied
to f as an unpaired seq:
(mapply (fn [x & {:keys [y z]}] (str x y z)) 1 {:y 2 :z 3})
where fn will receive args as: (1 :y 2 :z 3).
Like `apply` but assumes last arg is a map whose elements should be applied
to `f` as an unpaired seq:
(mapply (fn [x & {:keys [y z]}] (str x y z)) 1 {:y 2 :z 3})
where fn will receive args as: `(1 :y 2 :z 3)`.(max* n1 n2)(memoize* f)(memoize* ttl-ms f)(memoize* cache-size ttl-ms f)Like clojure.core/memoize but:
ttl-ms option.:mem/del or :mem/fresh.cache-size option.Like `clojure.core/memoize` but: * Uses delays to prevent race conditions on writes. * Supports auto invalidation & gc with `ttl-ms` option. * Supports manual invalidation by prepending args with `:mem/del` or `:mem/fresh`. * Supports cache size limit & gc with `cache-size` option.
(memoize1 f)Great for Reactjs render op caching on mobile devices, etc.
Great for Reactjs render op caching on mobile devices, etc.
(memoize_ f)As clojure.core/memoize but uses delays to avoid write races.
As `clojure.core/memoize` but uses delays to avoid write races.
(memoized cache f & args)Like (memoize* f) but takes an explicit cache atom (possibly nil)
and immediately applies memoized f to given arguments.
Like `(memoize* f)` but takes an explicit cache atom (possibly nil) and immediately applies memoized f to given arguments.
(merge-keywords ks & [no-slash?])(merge-url-with-query-string url m)(min* n1 n2)(ms & {:as opts :keys [years months weeks days hours mins secs msecs ms]})Returns number of milliseconds in period defined by given args.
Returns number of milliseconds in period defined by given args.
(ms->secs ms)(name-with-attrs name macro-args)Handles optional docstrings & attr maps for a macro def's name.
Stolen from clojure.tools.macro.
Handles optional docstrings & attr maps for a macro def's name. Stolen from `clojure.tools.macro`.
(nblank-str? x)(nblank? x)(nested-merge-with f & maps)(nil->str x)(nneg-int? x)(nneg-num? x)(nneg? x)(nnil-set x)(nnil= x y)(nnil= x y & more)(nnil? x)(norm-word-breaks s)Converts all word breaks of any form and length (including line breaks of any form, tabs, spaces, etc.) to a single regular space.
Converts all word breaks of any form and length (including line breaks of any form, tabs, spaces, etc.) to a single regular space.
(now-dt)(now-udt)(now-udt-mock-fn & [mock-udts])Useful for testing.
Useful for testing.
(nvec? n x)(parse-query-params s & [keywordize? encoding])Based on ring-codec/form-decode.
Based on `ring-codec/form-decode`.
(path & parts)Joins string paths (URLs, file paths, etc.) ensuring correct "/" interposition.
Joins string paths (URLs, file paths, etc.) ensuring correct "/" interposition.
(pos-int? x)(pos-num? x)(pow n exp)(qb & args)(qb-min-times times)(qbench nlaps form)(qbench nlaps form & more)Quick bench. Returns fastest of 3 sets of lap times for each form, in msecs.
Quick bench. Returns fastest of 3 sets of lap times for each form, in msecs.
(queue* & items)(queue? x)(rate-limit specs f)(rate-limited ncalls-limit window-ms f)(rate-limiter ncalls-limit window-ms)(rate-limiter* specs)Takes one or more rate specs of form [ncalls-limit window-ms ?spec-id] and
returns a (fn [& [req-id])) that returns nil (=> all rate limits passed), or
[<ms-wait> <worst-offending-spec-id>] / <ms-wait>.
Takes one or more rate specs of form [ncalls-limit window-ms ?spec-id] and returns a (fn [& [req-id])) that returns `nil` (=> all rate limits passed), or [<ms-wait> <worst-offending-spec-id>] / <ms-wait>.
(re-pattern? x)(read-edn s)(remove-vals pred m)Smaller, common-case version of filter-vals. Esp useful with nil?/blank?
pred when constructing maps: {:foo (when _ <...>) :bar (when _ <...>)} in a
way that preservers :or semantics.
Smaller, common-case version of `filter-vals`. Esp useful with `nil?`/`blank?`
pred when constructing maps: {:foo (when _ <...>) :bar (when _ <...>)} in a
way that preservers :or semantics.(removev pred coll)(repeatedly* n & body)(repeatedly-into coll n f)Like repeatedly but faster and conjs items into given collection.
Like `repeatedly` but faster and `conj`s items into given collection.
(repeatedly-into* coll n & body)(replace-in m & ops)Experimental. For use with swap!, etc.
Experimental. For use with `swap!`, etc.
(reportf fmt & xs)(reset-in! atom_ ks new-val)(reset-in! atom_ ks new-val & more)Is to reset! as swap-in! is to swap!.
Is to `reset!` as `swap-in!` is to `swap!`.
(round n & [type nplaces])(sayf fmt & xs)(sayp & xs)(secs->ms secs)(seq {:a :A}) => ([:a :A]) (seq-kvs {:a :A}) => (:a :A)
(seq {:a :A}) => ([:a :A])
(seq-kvs {:a :A}) => (:a :A)(set* x)(set-exp-backoff-timeout! nullary-f & [nattempt])(singleton? coll)(spaced-str xs)(spaced-str-with-nils xs)(str-?index s substr & [start-idx last?])(str-contains? s substr)(str-ends-with? s substr)(str-starts-with? s substr)(stringy? x)(sub-indexes x start-idx & {:keys [max-len end-idx]})Returns [<inclusive-start-idx*> <exclusive-end-idx*>] for counted 0-indexed input (str, vec, etc.) with support for:
Returns [<inclusive-start-idx*> <exclusive-end-idx*>] for counted 0-indexed
input (str, vec, etc.) with support for:
* Clamping of indexes beyond limits.
* Max-length -> end-index.
* -ive indexes (as +ive indexes but work from back of input):
(+0) (+1) (+2) (+3) (+4) ; inclusive +ive indexes
h e l l o ; 5 count
(-5) (-4) (-3) (-2) (-1) ; inclusive -ive indexes(substr s start-idx & [?max-len])Gives a consistent, flexible, cross-platform substring API built on
sub-indexes.
Gives a consistent, flexible, cross-platform substring API built on `sub-indexes`.
(subvec* v start-idx & [?max-len])Like subvec but uses sub-indexes.
Like `subvec` but uses `sub-indexes`.
(swap-in! atom_ ks f)(swap-in! atom_ ks f & more)More powerful version of swap!:
update-in semantics.(swapped <new-val> <return-val>) rather than just
<new-val>. This is useful when writing atomic pull fns, etc.More powerful version of `swap!`: * Supports optional `update-in` semantics. * Swap fn can return `(swapped <new-val> <return-val>)` rather than just <new-val>. This is useful when writing atomic pull fns, etc.
(swap-val! atom_ k f)Swaps associative value at key and returns the new value.
Specialized, fast swap-in! for use mostly by memoization utils.
Swaps associative value at key and returns the new value. Specialized, fast `swap-in!` for use mostly by memoization utils.
(swapped new-val return-val)(swapped* x)(swapped? x)(takev n coll)(thread-local-proxy & body)Thread-safe proxy wrapper, Ref. http://goo.gl/CEBJnQ (instant.clj).
Thread-safe proxy wrapper, Ref. http://goo.gl/CEBJnQ (instant.clj).
(time-ms & body)Returns number of milliseconds it takes to execute body.
Returns number of milliseconds it takes to execute body.
(time-ns & body)Returns number of nanoseconds it takes to execute body.
Returns number of nanoseconds it takes to execute body.
(tracef fmt & xs)(undefined->nil x)(url-decode s & [encoding])Stolen from http://goo.gl/99NSR1.
Stolen from http://goo.gl/99NSR1.
(url-encode s)Stolen from http://goo.gl/99NSR1.
Stolen from http://goo.gl/99NSR1.
(uuid-str)(uuid-str max-length)Returns a UUIDv4 string of form "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx", Ref. http://www.ietf.org/rfc/rfc4122.txt, https://gist.github.com/franks42/4159427
Returns a UUIDv4 string of form "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx",
Ref. http://www.ietf.org/rfc/rfc4122.txt,
https://gist.github.com/franks42/4159427(vec* x)(vec2? x)(vec3? x)(vsplit-first v)(warnf fmt & xs)(when-lets bindings & body)Like when-let but binds multiple values iff all tests are true.
Like `when-let` but binds multiple values iff all tests are true.
(xdistinct)(xdistinct keyfn)(xdistinct keyfn coll)distinctv` transducer.
distinctv` transducer.
(zero-num? x)cljdoc builds & hosts documentation for Clojure/Script libraries
| Ctrl+k | Jump to recent docs |
| ← | Move to previous article |
| → | Move to next article |
| Ctrl+/ | Jump to the search field |