Extended core library for Clojure/Script that emphasizes:
This lib's mostly for my own use and for advanced users that feel comfortable reading this source. Not providing much beginner-oriented documentation for this, sorry.
Quick Taoensso naming conventions:
foo - Dynamic var
foo! - Fn with side effects, or that should otherwise be used cautiously
foo? - Truthy val or fn that returns truthy val
foo!? - Fn that has side effects (or requires caution) and that return
a truthy val. Note: !?, not ?!
foo$ - Fn that's notably expensive to compute (e.g. hits db)
foo_ - Derefable val (e.g. atom, volatile, delay, etc.)
foo__ - Derefable in a derefable (e.g. delay in an atom), etc.
_ - Unnamed val
_foo - Named but unused val
?foo - Optional val (emphasize that val may be nil)
foo* - A variation of foo
(e.g. foo*
macro vs foo
fn)
foo' - ''
-foo - Public implementation detail or intermediate (e.g. uncoerced) val
foo - Val "to foo" (e.g. >sender, >host), or fn to put/coerce/transform <foo - Val "from foo" (e.g. <sender, <host), or fn to take/coerce/transform ->foo - Fn to put/coerce/transform
Type affixes may be used for clarity: <prefix>-<name> - m-users, v-users, n-users, etc. (also nusers when unambiguous) <name>-<postfix> - users-map, users-vec, user-count, etc.
Regarding name heirarchy:
When there's a significant num of syms with a meaningful hierarchy,
prefer names with descending hierarchy to emphasize structure and
related groups/functionality, e.g.:
user-add
, user-remove
, user-mod
vs
add-user
, remove-user
, mod-user
, etc.
Commit message tags (in priority order): [wip] - Work-in-progress (still under development)
[mod] - Modify behaviour (=> breaking), [mod!], [mod!!], etc. for attention [fix] - Fix broken behaviour (=> usu. non-breaking) [new] - Add new behaviour (=> non-breaking)
[doc] - Documentation changes besides those better labelled as [mod], [fix], or [new] [nop] - Other non-breaking changes (to implementation details, non-code changes, etc.)
[x] [y] - Single commit with multiple tags (in priority order), try avoid
Example commit messages: v1.0.0 (2022-01-27) ; Tagged release [new] [#122] Add new feature x (@contributor)
Version numbers: Ver tables: X.Y.Z (without backticks) Min ver: vX.Y.Z+ Elsewhere: vX.Y.Z
Extended core library for Clojure/Script that emphasizes: * Cross-platform API * Flexibility * Performance * Backwards compatibility This lib's mostly for my own use and for advanced users that feel comfortable reading this source. Not providing much beginner-oriented documentation for this, sorry. Quick Taoensso naming conventions: **foo** - Dynamic var foo! - Fn with side effects, or that should otherwise be used cautiously foo? - Truthy val or fn that returns truthy val foo!? - Fn that has side effects (or requires caution) and that return a truthy val. Note: !?, not ?! foo$ - Fn that's notably expensive to compute (e.g. hits db) foo_ - Derefable val (e.g. atom, volatile, delay, etc.) foo__ - Derefable in a derefable (e.g. delay in an atom), etc. _ - Unnamed val _foo - Named but unused val ?foo - Optional val (emphasize that val may be nil) foo* - A variation of `foo` (e.g. `foo*` macro vs `foo` fn) foo' - '' -foo - Public implementation detail or intermediate (e.g. uncoerced) val >foo - Val "to foo" (e.g. >sender, >host), or fn to put/coerce/transform <foo - Val "from foo" (e.g. <sender, <host), or fn to take/coerce/transform ->foo - Fn to put/coerce/transform Type affixes may be used for clarity: <prefix>-<name> - m-users, v-users, n-users, etc. (also nusers when unambiguous) <name>-<postfix> - users-map, users-vec, user-count, etc. Regarding name heirarchy: When there's a significant num of syms with a meaningful hierarchy, prefer names with descending hierarchy to emphasize structure and related groups/functionality, e.g.: `user-add`, `user-remove`, `user-mod` vs `add-user`, `remove-user`, `mod-user`, etc. Commit message tags (in priority order): [wip] - Work-in-progress (still under development) [mod] - Modify behaviour (=> breaking), [mod!], [mod!!], etc. for attention [fix] - Fix broken behaviour (=> usu. non-breaking) [new] - Add new behaviour (=> non-breaking) [doc] - Documentation changes besides those better labelled as [mod], [fix], or [new] [nop] - Other non-breaking changes (to implementation details, non-code changes, etc.) [x] [y] - Single commit with multiple tags (in priority order), try avoid Example commit messages: v1.0.0 (2022-01-27) ; Tagged release [new] [#122] Add new feature x (@contributor) Version numbers: Ver tables: X.Y.Z (without backticks) Min ver: vX.Y.Z+ Elsewhere: vX.Y.Z
(<* x y z)
(<=* x y z)
(>* x y z)
(>=* x y z)
(abbreviate-ns x)
(abbreviate-ns n-full x)
Give any nameable type (string, keyword, symbol), returns the same
type with at most n-full
(default 1) unabbreviated namespace parts.
Example: (abbreviate-ns 0 :foo.bar/baz) => :f.b/baz (abbreviate-ns 1 'foo.bar/baz) => 'f.bar/baz (abbreviate-ns 2 "foo.bar/baz") => "foo.bar/baz"
Give any nameable type (string, keyword, symbol), returns the same type with at most `n-full` (default 1) unabbreviated namespace parts. Example: (abbreviate-ns 0 :foo.bar/baz) => :f.b/baz (abbreviate-ns 1 'foo.bar/baz) => 'f.bar/baz (abbreviate-ns 2 "foo.bar/baz") => "foo.bar/baz"
(abs n)
(after-timeout msecs & body)
Alpha, subject to change. Returns a TimeoutFuture that will execute body after timeout. Body must be non-blocking or cheap.
Alpha, subject to change. Returns a TimeoutFuture that will execute body after timeout. Body must be non-blocking or cheap.
(ajax-call url
{:keys [method params headers timeout-ms resp-type with-credentials?
xhr-pool xhr-cb-fn xhr-timeout-ms]
:as opts
:or {method :get
timeout-ms 10000
resp-type :auto
xhr-pool default-xhr-pool_
xhr-timeout-ms 2500}}
callback-fn)
Queues a lightweight Ajax call with Google Closure's goog.net.XhrIo
and
returns nil, or the resulting goog.net.XhrIo
instance if one was
immediately available from the XHR pool:
(ajax-call "http://localhost:8080/my-post-route" ; Endpoint URL
{:method :post ; ∈ #{:get :post :put}
:resp-type :text ; ∈ #{:auto :edn :json :xml :text}
:params {:username "Rich Hickey" :type "Awesome"} ; Request params
:headers {"Content-Type" "text/plain"} ; Request headers
:timeout-ms 7000
:with-credentials? false ; Enable if using CORS (requires xhr v2+)
:xhr-pool my-xhr-pool ; Optional `goog.net.XhrIoPool` instance or delay
:xhr-cb-fn (fn [xhr]) ; Optional fn to call with `XhrIo` from pool when available
:xhr-timeout-ms 2500 ; Optional max msecs to wait on pool for `XhrIo`
}
(fn ajax-callback-fn [resp-map]
(let [{:keys [success? ?status ?error ?content ?content-type]} resp-map]
;; ?status ; ∈ #{nil 200 404 ...}, non-nil iff server responded
;; ?error ; ∈ #{nil <http-error-status-code> <exception> :timeout
:abort :http-error :exception :xhr-pool-depleted}
(js/alert (str "Ajax response: " resp-map)))))
Queues a lightweight Ajax call with Google Closure's `goog.net.XhrIo` and returns nil, or the resulting `goog.net.XhrIo` instance if one was immediately available from the XHR pool: (ajax-call "http://localhost:8080/my-post-route" ; Endpoint URL {:method :post ; ∈ #{:get :post :put} :resp-type :text ; ∈ #{:auto :edn :json :xml :text} :params {:username "Rich Hickey" :type "Awesome"} ; Request params :headers {"Content-Type" "text/plain"} ; Request headers :timeout-ms 7000 :with-credentials? false ; Enable if using CORS (requires xhr v2+) :xhr-pool my-xhr-pool ; Optional `goog.net.XhrIoPool` instance or delay :xhr-cb-fn (fn [xhr]) ; Optional fn to call with `XhrIo` from pool when available :xhr-timeout-ms 2500 ; Optional max msecs to wait on pool for `XhrIo` } (fn ajax-callback-fn [resp-map] (let [{:keys [success? ?status ?error ?content ?content-type]} resp-map] ;; ?status ; ∈ #{nil 200 404 ...}, non-nil iff server responded ;; ?error ; ∈ #{nil <http-error-status-code> <exception> :timeout :abort :http-error :exception :xhr-pool-depleted} (js/alert (str "Ajax response: " resp-map)))))
(approx== x y)
(approx== signf x y)
(as-?bool x)
(as-?email ?s)
(as-?email max-len ?s)
(as-?float x)
(as-?int x)
(as-?kw x)
(as-?name x)
(as-?nat-float x)
(as-?nat-int x)
(as-?nblank x)
(as-?nblank-trim x)
(as-?nemail ?s)
(as-?nemail max-len ?s)
(as-?nempty-str x)
(as-?nzero x)
(as-?pnum x)
(as-?pos-float x)
(as-?pos-int x)
(as-?qname x)
(as-?rnum x)
(as-?udt x)
(as-bool x)
(as-email x)
(as-email n x)
(as-float x)
(as-int x)
(as-kw x)
(as-name x)
(as-nat-float x)
(as-nat-int x)
(as-nblank x)
(as-nblank-trim x)
(as-nemail x)
(as-nemail n x)
(as-nempty-str x)
(as-nzero x)
(as-pnum x)
(as-pnum! x)
(as-pnum-complement x)
(as-pos-float x)
(as-pos-int x)
(as-qname x)
(as-rnum x)
(as-rnum! x)
(as-udt x)
(assert-min-encore-version min-version)
Version check for dependency conflicts, etc.
Version check for dependency conflicts, etc.
(assoc-nx m kvs)
(assoc-nx m k v)
(assoc-nx m k v & kvs)
Assocs each kv iff its key doesn't already exist.
Assocs each kv iff its key doesn't already exist.
(assoc-some m kvs)
(assoc-some m k v)
(assoc-some m k v & kvs)
Assocs each kv iff its value is not nil.
Assocs each kv iff its value is not nil.
(assoc-when m kvs)
(assoc-when m k v)
(assoc-when m k v & kvs)
Assocs each kv iff its val is truthy.
Assocs each kv iff its val is truthy.
(atom? x)
(ba->hex-str ba)
Returns byte[] for given hex string.
Returns byte[] for given hex string.
(ba-concat ba1 ba2)
(ba-hash x)
Returns hash int of given byte[].
Returns hash int of given byte[].
(ba-split ba idx)
(ba= x y)
Returns true iff given two byte[]s with the same content.
Returns true iff given two byte[]s with the same content.
(bench nlaps opts & body)
(bench* nlaps
{:keys [nlaps-warmup nthreads as-ns?] :or {nlaps-warmup 0 nthreads 1}}
f)
Repeatedly executes fn and returns time taken to complete execution.
Repeatedly executes fn and returns time taken to complete execution.
(boolean? x)
(bytes? x)
Returns true iff given byte[] argument.
Returns true iff given byte[] argument.
(cache f)
(cache {:keys [size ttl-ms gc-every] :as opts} f)
Returns a cached version of given referentially transparent function f
.
Like core/memoize
but:
Often faster, depending on options.
Prevents race conditions on writes.
Supports cache invalidation by prepending args with:
:cache/del
; Delete cached item for subsequent args, returns nil.:cache/fresh
; Renew cached item for subsequent args, returns new val.Supports options:
ttl-ms
; Expire cached items after <this> many msecs.
size
; Restrict cache size to <this> many items at the next garbage
; collection (GC).
gc-every
; Run garbage collection (GC) approximately once every
; <this> many calls to cached fn. If unspecified, GC rate
; will be determined automatically based on size
.
See also defn-cached
, fmemoize
, memoize-last
.
Returns a cached version of given referentially transparent function `f`. Like `core/memoize` but: - Often faster, depending on options. - Prevents race conditions on writes. - Supports cache invalidation by prepending args with: - `:cache/del` ; Delete cached item for subsequent args, returns nil. - `:cache/fresh` ; Renew cached item for subsequent args, returns new val. - Supports options: - `ttl-ms` ; Expire cached items after <this> many msecs. - `size` ; Restrict cache size to <this> many items at the next garbage ; collection (GC). - `gc-every` ; Run garbage collection (GC) approximately once every ; <this> many calls to cached fn. If unspecified, GC rate ; will be determined automatically based on `size`. See also `defn-cached`, `fmemoize`, `memoize-last`.
(call-after-timeout msecs f)
(call-after-timeout impl_ msecs f)
Alpha, subject to change.
Returns a TimeoutFuture that will execute f
after given msecs.
Does NOT do any automatic binding conveyance.
Performance depends on the provided timer implementation (impl_
).
The default implementation offers O(logn) add, O(1) cancel, O(1) tick.
See ITimeoutImpl
for extending to arbitrary timer implementations.
Alpha, subject to change. Returns a TimeoutFuture that will execute `f` after given msecs. Does NOT do any automatic binding conveyance. Performance depends on the provided timer implementation (`impl_`). The default implementation offers O(logn) add, O(1) cancel, O(1) tick. See `ITimeoutImpl` for extending to arbitrary timer implementations.
(can-meta? x)
(case-eval expr & clauses)
Like case
but evals test constants for their compile-time value.
Like `case` but evals test constants for their compile-time value.
(case-insensitive-str= s1 s2)
Returns true iff given strings are equal, ignoring case.
Returns true iff given strings are equal, ignoring case.
(catching try-expr)
(catching try-expr error-sym catch-expr)
(catching try-expr error-sym catch-expr finally-expr)
(catching try-expr error-type error-sym catch-expr finally-expr)
Terse, cross-platform try/catch/finally
.
See also try*
for more flexibility.
Terse, cross-platform `try/catch/finally`. See also `try*` for more flexibility.
(catching-rf rf)
(catching-rf error-fn rf)
Returns wrapper around given reducing function rf
so that if rf
throws, (error-fn <thrown-error> <contextual-data>) will be called.
The default error-fn
will rethrow the original error, wrapped in
extra contextual information to aid debugging.
See also catching-xform
.
Returns wrapper around given reducing function `rf` so that if `rf` throws, (error-fn <thrown-error> <contextual-data>) will be called. The default `error-fn` will rethrow the original error, wrapped in extra contextual information to aid debugging. See also `catching-xform`.
(catching-xform xform)
(catching-xform error-fn xform)
Like catching-rf
, but applies to a transducer (xform
).
Makes debugging transductions much easier by greatly improving
the information provided in any errors thrown by xform
or the
reducing fn:
(transduce (catching-xform (comp (filter even?) (map inc))) ; Modified xform <reducing-fn> <...>)
Like `catching-rf`, but applies to a transducer (`xform`). Makes debugging transductions much easier by greatly improving the information provided in any errors thrown by `xform` or the reducing fn: (transduce (catching-xform (comp (filter even?) (map inc))) ; Modified xform <reducing-fn> <...>)
(caught-error-data & body)
Handy for error-throwing unit tests.
Handy for error-throwing unit tests.
(chan? x)
Returns true iff given a clojure.core.async
channel.
Returns true iff given a `clojure.core.async` channel.
(chance prob)
Returns true with probability ∈ ℝ[0,1].
Returns true with probability ∈ ℝ[0,1].
(check-all test)
(check-all test & more)
Returns all logical false/throwing expressions (ids/forms), or nil.
Returns all logical false/throwing expressions (ids/forms), or nil.
(check-some test)
(check-some test & more)
Returns first logical false/throwing expression (id/form), or nil.
Returns first logical false/throwing expression (id/form), or nil.
(clamp nmin nmax n)
(clamp* nmin nmax n)
(clamp-float nmin nmax n)
(clamp-int nmin nmax n)
(compile-if test then)
(compile-if test then else)
Evaluates test
. If it returns logical true (and doesn't throw), expands
to then
, otherwise expands to else
.
Evaluates `test`. If it returns logical true (and doesn't throw), expands to `then`, otherwise expands to `else`.
(compile-when test & body)
(compiling-cljs?)
Return truthy iff currently generating Cljs code.
See also if-cljs
, if-clj
.
Return truthy iff currently generating Cljs code. See also `if-cljs`, `if-clj`.
(cond & clauses)
Like core/cond
but supports implicit final else
clause, and special
clause keywords for advanced behaviour:
(cond :let [x "x"] ; Establish let binding/s for remaining forms :binding [x "x"] ; Establish dynamic binding/s for remaining forms :do (println (str "x value: " x)) ; Eval expr for side effects
:if-let [y "y" z nil] "y and z were both truthy"
:if-some [y "y" z nil] "y and z were both non-nil")
:let support inspired by https://github.com/Engelberg/better-cond. Simple, flexible way to eliminate deeply-nested control flow code.
Like `core/cond` but supports implicit final `else` clause, and special clause keywords for advanced behaviour: (cond :let [x "x"] ; Establish let binding/s for remaining forms :binding [*x* "x"] ; Establish dynamic binding/s for remaining forms :do (println (str "x value: " x)) ; Eval expr for side effects :if-let [y "y" z nil] "y and z were both truthy" :if-some [y "y" z nil] "y and z were both non-nil") :let support inspired by <https://github.com/Engelberg/better-cond>. Simple, flexible way to eliminate deeply-nested control flow code.
(cond! & clauses)
Like cond
but throws on non-match like case
and condp
.
Like `cond` but throws on non-match like `case` and `condp`.
(conj-some)
(conj-some coll)
(conj-some coll x)
(conj-some coll x & more)
Conjoins each non-nil value.
Conjoins each non-nil value.
(conj-when)
(conj-when coll)
(conj-when coll x)
(conj-when coll x & more)
Conjoins each truthy value.
Conjoins each truthy value.
(const-ba= ba1 ba2)
Constant-time ba=
.
Useful to prevent timing attacks, etc.
Constant-time `ba=`. Useful to prevent timing attacks, etc.
(const-str= s1 s2)
Constant-time string equality checker. Useful to prevent timing attacks, etc.
Constant-time string equality checker. Useful to prevent timing attacks, etc.
(contains-in? coll ks)
(contains-in? coll ks k)
(convey-reduced x)
(count-words s)
(counter)
(counter init)
Returns a fast atomic Counter with init
initial int value:
Experimental 3-arity version takes an action
:
:add, :set, :set-get, :get-set, :get-add, :add-get
Returns a fast atomic Counter with `init` initial int value: - (<counter> ) -> add 1, return old val - (<counter> <n>) -> add n, return old val Experimental 3-arity version takes an `action`: :add, :set, :set-get, :get-set, :get-add, :add-get
(declare-remote & syms)
Declares given ns-qualified symbols, preserving metadata. Useful for circular dependencies.
Declares given ns-qualified symbols, preserving metadata. Useful for circular dependencies.
(def* sym & args)
Like core/def
but supports attrs map.
Like `core/def` but supports attrs map.
(defalias src-sym)
(defalias alias-sym src-sym)
(defalias alias-sym src-sym alias-attrs)
(defalias alias-sym src-sym alias-attrs alias-body)
Defines a local alias for the var identified by given qualified source symbol: (defalias my-map clojure.core/map), etc.
For Clj:
Defines a local alias for the var identified by given qualified source symbol: (defalias my-map clojure.core/map), etc. For Clj: - Source var's metadata will be preserved (docstring, arglists, etc.). - Changes to source var's value will also be applied to alias.
(defaliases {:keys [alias src attrs body]} ...)
Bulk version of defalias
.
Takes source symbols or {:keys [alias src attrs body]} maps:
(defaliases
{:alias my-map, :src map, :attrs {:doc "My map
alias"}}
{:alias my-vec, :src vec, :attrs {:doc "My vec
alias"}})
Bulk version of `defalias`. Takes source symbols or {:keys [alias src attrs body]} maps: (defaliases {:alias my-map, :src map, :attrs {:doc "My `map` alias"}} {:alias my-vec, :src vec, :attrs {:doc "My `vec` alias"}})
Simple one-timeout timeout implementation provided by platform timer. O(logn) add, O(1) cancel, O(1) tick. Fns must be non-blocking or cheap. Similar efficiency to core.async timers (binary heap vs DelayQueue).
Simple one-timeout timeout implementation provided by platform timer. O(logn) add, O(1) cancel, O(1) tick. Fns must be non-blocking or cheap. Similar efficiency to core.async timers (binary heap vs DelayQueue).
(defn-cached sym cache-opts & body)
Defines a cached function.
Like (def <sym> (cache <cache-opts> <body...>)), but preserves
:arglists (arity) metadata as with defn
:
(defn-cached ^:private my-fn {:ttl-ms 500} "Does something interesting, caches resultes for 500 msecs" [n] (rand-int n))
Defines a cached function. Like (def <sym> (cache <cache-opts> <body...>)), but preserves :arglists (arity) metadata as with `defn`: (defn-cached ^:private my-fn {:ttl-ms 500} "Does something interesting, caches resultes for 500 msecs" [n] (rand-int n))
(defonce sym & args)
Like core/defonce
but supports docstring and attrs map.
Like `core/defonce` but supports docstring and attrs map.
(defstub sym)
Experimental!!
Declares a stub var that can be initialized from any namespace with
unstub-<stub-name>
.
Decouples a var's declaration (location) and its initialization (value). Handy for defining vars in a shared ns from elsewhere (e.g. a private or cyclic ns).
Experimental!! Declares a stub var that can be initialized from any namespace with `unstub-<stub-name>`. Decouples a var's declaration (location) and its initialization (value). Handy for defining vars in a shared ns from elsewhere (e.g. a private or cyclic ns).
(deprecated & body)
Elides body when taoensso.elide-deprecated
JVM property or
TAOENSSO_ELIDE_DEPRECATED
environment variable is ∈ #{"true" "TRUE"}.
Elides body when `taoensso.elide-deprecated` JVM property or `TAOENSSO_ELIDE_DEPRECATED` environment variable is ∈ #{"true" "TRUE"}.
(derefable? x)
(dis-assoc-some m kvs)
(dis-assoc-some m k v)
(dis-assoc-some m k v & kvs)
Assocs each kv if its value is not nil, otherwise dissocs it.
Assocs each kv if its value is not nil, otherwise dissocs it.
(dissoc-in m ks)
(dissoc-in m ks dissoc-k)
(dissoc-in m ks dissoc-k & more)
(distinct-elements? x)
(do-false & body)
(do-nil & body)
(do-true & body)
(doto-cond [sym x] & clauses)
Cross between doto
, cond->
and as->
.
Cross between `doto`, `cond->` and `as->`.
(editable? x)
(ensure-set x)
(ensure-vec x)
(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)
(ex-cause ex)
Copy of core/ex-cause
(added in Clojure v1.10).
Copy of `core/ex-cause` (added in Clojure v1.10).
(ex-message ex)
Copy of core/ex-message
(added in Clojure v1.10).
Copy of `core/ex-message` (added in Clojure v1.10).
(exception? x)
(exp-backoff n-attempt)
(exp-backoff n-attempt {:keys [min max factor] :or {factor 1000}})
Returns binary exponential backoff value for n<=36.
Returns binary exponential backoff value for n<=36.
(explode-keyword k)
(fast-merge maps)
(fast-merge m1 m2)
(fast-merge m1 m2 m3)
(fast-merge m1 m2 m3 m4)
Like core/merge
but faster.
Single arity case takes a collection of maps.
Like `core/merge` but faster. Single arity case takes a collection of maps.
Returns true iff any files backing given named resources have changed since last call.
Returns true iff any files backing given named resources have changed since last call.
(filter-keys pred m)
(filter-vals pred m)
(finite-num? x)
Returns true iff given a number (of standard type) that is: finite (excl. NaN and infinities).
Returns true iff given a number (of standard type) that is: finite (excl. NaN and infinities).
(float? x)
Returns true iff given a number (of standard type) that is: a fixed-precision floating-point (incl. NaN and infinities).
Returns true iff given a number (of standard type) that is: a fixed-precision floating-point (incl. NaN and infinities).
(fmemoize f)
For Clj: fastest possible memoize. Non-racey, 0-7 arity only.
For Cljs: just passes through to core/memoize
.
For Clj: fastest possible memoize. Non-racey, 0-7 arity only. For Cljs: just passes through to `core/memoize`.
(format fmt & args)
Like core/format
but:
format
!).Like `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* xform fmt args)
(format-query-string m)
(future* form)
(future* executor-service form)
Experimental, subject to change without notice!
Like future
but supports use of given custom
java.util.concurrent.ExecutorService
.
Will default to using JVM 21+ virtual threads when possible, otherwise an unbounded fixed daemon thread pool.
See also future-call
, virtual-executor
, pool-executor
.
Experimental, subject to change without notice! Like `future` but supports use of given custom `java.util.concurrent.ExecutorService`. Will default to using JVM 21+ virtual threads when possible, otherwise an unbounded fixed daemon thread pool. See also `future-call`, `virtual-executor`, `pool-executor`.
(future-call* f)
(future-call* executor-service f)
Experimental, subject to change without notice!
Like future-call
but supports use of given custom
java.util.concurrent.ExecutorService
.
Will default to using JVM 21+ virtual threads when possible, otherwise an unbounded fixed daemon thread pool.
See also future
, virtual-executor
, pool-executor
.
Experimental, subject to change without notice! Like `future-call` but supports use of given custom `java.util.concurrent.ExecutorService`. Will default to using JVM 21+ virtual threads when possible, otherwise an unbounded fixed daemon thread pool. See also `future`, `virtual-executor`, `pool-executor`.
(future-pool n-threads)
Returns a simple semaphore-limited wrapper of Clojure's standard future
:
(fn future-pool-fn
([f] [timeout-msecs timeout-val f] [] [timeout-msecs timeout-val]))
Arities of returned function: [f] - Blocks to acquire a future, then executes (f) on that future. [ ] - Blocks to acquire ALL futures, then immediately releases them. Useful for blocking till all outstanding work completes.
[timeout-msecs timeout-val f] - Variant of [f] with timeout
[timeout-msecs timeout-val ] - Variant of [ ] with timeout
See also future*
for fully custom pools, etc.
Returns a simple semaphore-limited wrapper of Clojure's standard `future`: (fn future-pool-fn ([f] [timeout-msecs timeout-val f] [] [timeout-msecs timeout-val])) Arities of returned function: [f] - Blocks to acquire a future, then executes (f) on that future. [ ] - Blocks to acquire ALL futures, then immediately releases them. Useful for blocking till all outstanding work completes. [timeout-msecs timeout-val f] - Variant of [f] with timeout [timeout-msecs timeout-val ] - Variant of [ ] with timeout See also `future*` for fully custom pools, etc.
(get-dynamic-assertion-data)
Prefer get-data
Prefer `get-data`
(get-env)
(get-file-resource-?last-modified rname)
Returns last-modified time for file backing given named resource, or nil if file doesn't exist.
Returns last-modified time for file backing given named resource, or nil if file doesn't exist.
(get-hostname)
Returns local hostname string, or nil.
Returns local hostname string, or nil.
(get-pom-version dep-sym)
Returns POM version string for given Maven dependency, or nil.
Returns POM version string for given Maven dependency, or nil.
(get-source macro-form macro-env)
Returns {:keys [ns line column file]} source location given a macro's
compile-time &form
and &env
vals. See also keep-callsite
.
Returns {:keys [ns line column file]} source location given a macro's compile-time `&form` and `&env` vals. See also `keep-callsite`.
(get-substr-by-idx s start-idx)
(get-substr-by-idx s start-idx end-idx)
Returns ?substring from given string.
Like subs
but:
Returns nil when requested substring would be empty.
Returns ?substring from given string. Like `subs` but: - Provides consistent clj/s behaviour. - Never throws (snaps to valid indexes). - Indexes may be -ive (=> indexed from end of string). Returns nil when requested substring would be empty.
(get-substr-by-len s start-idx)
(get-substr-by-len s start-idx sub-len)
Returns ?substring from given string.
Like get-substr-by-idx
, but takes a substring-length 3rd argument.
Returns ?substring from given string. Like `get-substr-by-idx`, but takes a substring-length 3rd argument.
(get-subvec v start)
(get-subvec v start end)
Like subvec
but never throws (snaps to valid start and end indexes).
Like `subvec` but never throws (snaps to valid start and end indexes).
(get-subvector v start)
(get-subvector v start length)
Like get-subvec
but:
length
instead of end
(index).start
=> index from right of vector.Like `get-subvec` but: - Takes `length` instead of `end` (index). - -ive `start` => index from right of vector.
(get-truss-data)
Returns current value of dynamic assertion data.
Returns current value of dynamic assertion data.
(get-win-loc)
Returns current window location as {:keys [href protocol hostname host pathname search hash]}.
Returns current window location as {:keys [href protocol hostname host pathname search hash]}.
(get1 m k not-found)
(get1 m k1 k2 not-found)
(get1 m k1 k2 k3 not-found)
Like get
but returns val for first given key that exists in map.
Useful for key aliases or fallbacks when vals may be falsey.
Equivalent to (if (contains? m k1) (get m k1)
(if (contains? m k2) (get m k2) ...)).
Like `get` but returns val for first given key that exists in map. Useful for key aliases or fallbacks when vals may be falsey. Equivalent to (if (contains? m k1) (get m k1) (if (contains? m k2) (get m k2) ...)).
(have x)
(have pred (:in) x)
(have pred (:in) x & more-xs)
Takes a pred and one or more vals. Tests pred against each val, trapping errors. If any pred test fails, throws a detailed assertion error. Otherwise returns input val/vals for convenient inline-use/binding.
Respects assert value so tests can be elided from production for zero runtime costs.
Provides a small, simple, flexible feature subset to alternative tools like clojure.spec, core.typed, prismatic/schema, etc.
;; Will throw a detailed error message on invariant violation: (fn my-fn [x] (str/trim (have string? x)))
You may attach arbitrary debug info to assertion violations like:
(have string? x :data {:my-arbitrary-debug-info "foo"})
Re: use of Truss assertions within other macro bodies: Due to CLJ-865, call site information (e.g. line number) of outer macro will unfortunately be lost.
See keep-callsite
util for a workaround.
See also have?
, have!
.
Takes a pred and one or more vals. Tests pred against each val, trapping errors. If any pred test fails, throws a detailed assertion error. Otherwise returns input val/vals for convenient inline-use/binding. Respects *assert* value so tests can be elided from production for zero runtime costs. Provides a small, simple, flexible feature subset to alternative tools like clojure.spec, core.typed, prismatic/schema, etc. ;; Will throw a detailed error message on invariant violation: (fn my-fn [x] (str/trim (have string? x))) You may attach arbitrary debug info to assertion violations like: `(have string? x :data {:my-arbitrary-debug-info "foo"})` Re: use of Truss assertions within other macro bodies: Due to CLJ-865, call site information (e.g. line number) of outer macro will unfortunately be lost. See `keep-callsite` util for a workaround. See also `have?`, `have!`.
(have! x)
(have! pred (:in) x)
(have! pred (:in) x & more-xs)
Like have
but ignores assert value (so can never be elided). Useful
for important conditions in production (e.g. security checks).
Like `have` but ignores *assert* value (so can never be elided). Useful for important conditions in production (e.g. security checks).
(have!? x)
(have!? pred (:in) x)
(have!? pred (:in) x & more-xs)
Specialized cross between have?
and have!
. Not used often but can be
handy for semantic clarification and/or to improve multi-val performance
when the return vals aren't necessary.
WARNING: Do NOT use in :pre/:post conds since those are ALWAYS subject
to assert, directly contradicting the intention of the bang (!
) here.
Specialized cross between `have?` and `have!`. Not used often but can be handy for semantic clarification and/or to improve multi-val performance when the return vals aren't necessary. **WARNING**: Do NOT use in :pre/:post conds since those are ALWAYS subject to *assert*, directly contradicting the intention of the bang (`!`) here.
Is clojure.core.async
present (not necessarily loaded)?
Is `clojure.core.async` present (not necessarily loaded)?
Is taoensso.telemere
present (not necessarily loaded)?
Is `taoensso.telemere` present (not necessarily loaded)?
(have? x)
(have? pred (:in) x)
(have? pred (:in) x & more-xs)
Like have
but returns true
on successful tests. In particular, this
can be handy for use with :pre/:post conditions. Compare:
(fn my-fn [x] {:post [(have nil? %)]} nil) ; {:post [nil]} FAILS
(fn my-fn [x] {:post [(have? nil? %)]} nil) ; {:post [true]} passes as intended
Like `have` but returns `true` on successful tests. In particular, this can be handy for use with :pre/:post conditions. Compare: (fn my-fn [x] {:post [(have nil? %)]} nil) ; {:post [nil]} FAILS (fn my-fn [x] {:post [(have? nil? %)]} nil) ; {:post [true]} passes as intended
(hex-str->ba s)
Returns hex string for given byte[].
Returns hex string for given byte[].
(ident-hex-str obj)
Returns hex string of given Object's identityHashCode
(e.g. "0x5eeb49f2").
Returns hex string of given Object's `identityHashCode` (e.g. "0x5eeb49f2").
(ident? x)
(identical-kw? x y)
Returns true iff two keywords are identical.
Portable and maximally fast.
For Clj this expands to: (identical? x y)
For Cljs this expands to: (keyword-identical? x y)
Returns true iff two keywords are identical. Portable and maximally fast. For Clj this expands to: `(identical? x y)` For Cljs this expands to: `(keyword-identical? x y)`
(if-clj then & [else])
(if-cljs then & [else])
(if-let bindings then)
(if-let bindings then else)
Like core/if-let
but can bind multiple values for then
iff all tests
are truthy, supports internal unconditional :let
s.
Like `core/if-let` but can bind multiple values for `then` iff all tests are truthy, supports internal unconditional `:let`s.
(if-not test-or-bindings then)
(if-not test-or-bindings then else)
Like core/if-not
but acts like if-let
when given a binding vector
as test expr.
Like `core/if-not` but acts like `if-let` when given a binding vector as test expr.
(if-some bindings then)
(if-some bindings then else)
Like core/if-some
but can bind multiple values for then
iff all tests
are non-nil, supports internal unconditional :let
s.
Like `core/if-some` but can bind multiple values for `then` iff all tests are non-nil, supports internal unconditional `:let`s.
(indexed? x)
(inst? x)
(instance! class arg)
(instance! class arg {:keys [msg context param ...]})
(instance! class arg & {:keys [msg context param ...]})
If (instance? class arg) is true, returns arg.
Otherwise throws runtime ExceptionInfo
with unexpected-arg!
.
See unexpected-arg!
for more info.
If (instance? class arg) is true, returns arg. Otherwise throws runtime `ExceptionInfo` with `unexpected-arg!`. See `unexpected-arg!` for more info.
(int? x)
Returns true iff given a number (of standard type) that is: a fixed-precision integer.
Returns true iff given a number (of standard type) that is: a fixed-precision integer.
(interleave-all)
(interleave-all c1)
(interleave-all c1 c2)
(interleave-all c1 c2 & colls)
Like interleave
but includes all items (i.e. stops when the longest
rather than shortest coll has been consumed).
Like `interleave` but includes all items (i.e. stops when the longest rather than shortest coll has been consumed).
(interns-overview)
(interns-overview ns)
Returns {:keys [api public private impl test no-doc]}, with each key mapped to an alphabetical list of the relevant vars in given namespace.
"impl" vars are public vars with names that begin with "-" or "_", a naming convention commonly used to indicate vars intended to be treated as private implementation details even when public.
Returns {:keys [api public private impl test no-doc]}, with each key mapped to an alphabetical list of the relevant vars in given namespace. "impl" vars are public vars with names that begin with "-" or "_", a naming convention commonly used to indicate vars intended to be treated as private implementation details even when public.
(into! to from)
(into! to xform from)
(into-all to from)
(into-all to from & more)
Like into
but supports multiple "from"s.
Like `into` but supports multiple "from"s.
(into-str & xs)
Simple Hiccup-like string templating to complement Tempura.
Simple Hiccup-like string templating to complement Tempura.
(invert-map m)
(is! x)
(is! pred x)
(is! pred x data)
Lightweight have!
that provides less diagnostic info.
Lightweight `have!` that provides less diagnostic info.
(tf-cancel! _)
Returns true iff the timeout was successfully cancelled (i.e. was previously pending).
Returns true iff the timeout was successfully cancelled (i.e. was previously pending).
(tf-cancelled? _)
Returns true iff the timeout is cancelled.
Returns true iff the timeout is cancelled.
(tf-done? _)
Returns true iff the timeout is not pending (i.e. has a completed result or is cancelled).
Returns true iff the timeout is not pending (i.e. has a completed result or is cancelled).
(tf-pending? _)
Returns true iff the timeout is pending.
Returns true iff the timeout is pending.
(tf-poll _)
Returns :timeout/pending, :timeout/cancelled, or the timeout's completed result.
Returns :timeout/pending, :timeout/cancelled, or the timeout's completed result.
(tf-state _)
Returns a map of timeout's public state.
Returns a map of timeout's public state.
(-schedule-timeout _ msecs f)
(keep-callsite & body)
The long-standing CLJ-865 unfortunately means that it's currently not possible for an inner macro to access the &form metadata of an outer macro.
This means that inner macros lose call site information like the line number of the outer macro.
This util offers a workaround for macro authors:
(defmacro inner [] (meta &form))
(defmacro outer1 [] (inner)) (defmacro outer2 [] (keep-callsite
(inner)))
(inner) => {:line _, :column _} (outer1) => nil (outer2) => {:line _, :column _}
The long-standing CLJ-865 unfortunately means that it's currently not possible for an inner macro to access the &form metadata of an outer macro. This means that inner macros lose call site information like the line number of the outer macro. This util offers a workaround for macro authors: (defmacro inner [] (meta &form)) (defmacro outer1 [] `(inner)) (defmacro outer2 [] (keep-callsite `(inner))) (inner) => {:line _, :column _} (outer1) => nil (outer2) => {:line _, :column _}
(keys-by f coll)
Returns {(f x) x} map for xs in coll
.
Returns {(f x) x} map for xs in `coll`.
(ks-nnil? ks m)
(ks<= ks m)
(ks= ks m)
(ks>= ks m)
(lazy-seq? x)
(logf fmt & xs)
(logp & xs)
(map-keys f m)
(map-vals f m)
(mapply f & args)
Like apply
but calls seq-kvs
on final arg.
Like `apply` but calls `seq-kvs` on final arg.
(matching-error err)
(matching-error err-type err)
(matching-error err-type err-pattern err)
Given an error (e.g. Throwable) and matching criteria. Returns the error if it matches all criteria, otherwise returns nil.
err-type
may be:
ArithmeticException
, AssertionError
, etc.):all
=> any platform error (Throwable or js/Error, etc.):common
=> common platform error (Exception or js/Error):ex-info
=> a ExceptionInfo
as created by ex-info
pattern
may be:
ex-message
must matchex-data
must match using submap?
patterns
as above, at least one of which must matchWhen an error with (nested) causes doesn't match, a match will be attempted against its (nested) causes.
Low-level util, see also throws
, throws?
.
Given an error (e.g. Throwable) and matching criteria. Returns the error if it matches all criteria, otherwise returns nil. `err-type` may be: - A predicate function, (fn match? [x]) -> bool - A class (e.g. `ArithmeticException`, `AssertionError`, etc.) - `:all` => any platform error (Throwable or js/Error, etc.) - `:common` => common platform error (Exception or js/Error) - `:ex-info` => a `ExceptionInfo` as created by `ex-info` `pattern` may be: - A string or Regex against which `ex-message` must match - A map against which `ex-data` must match using `submap?` - A set of `patterns` as above, at least one of which must match When an error with (nested) causes doesn't match, a match will be attempted against its (nested) causes. Low-level util, see also `throws`, `throws?`.
(max* n1 n2)
(memoize f)
(memoize ttl-ms f)
(memoize size ttl-ms f)
Alternative way to call cache
, provided mostly for back compatibility.
See cache
docstring for details.
Alternative way to call `cache`, provided mostly for back compatibility. See `cache` docstring for details.
(memoize-last f)
Like core/memoize
but only caches the fn's most recent call.
Great for Reactjs render op caching on mobile devices, etc.
Like `core/memoize` but only caches the fn's most recent call. Great for Reactjs render op caching on mobile devices, etc.
(merge & maps)
Like core/merge
but faster, supports :merge/dissoc
rvals.
Like `core/merge` but faster, supports `:merge/dissoc` rvals.
(merge-keywords ks)
(merge-keywords ks omit-slash?)
(merge-meta x m)
(merge-url-with-query-string url m)
(merge-with f & maps)
Like core/merge-with
but faster, supports :merge/dissoc
rvals.
Like `core/merge-with` but faster, supports `:merge/dissoc` rvals.
(min* n1 n2)
(ms opts)
(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)
(msecs opts)
(msecs & {:as opts :keys [years months weeks days hours mins secs msecs ms]})
Macro version of ms
.
Macro version of `ms`.
(name-filter spec)
Given filter spec
, returns a compiled (fn conform? [name]) that takes
any nameable type (string, keyword, symbol).
Spec may be:
A regex pattern. Will conform on match.
A str/kw/sym, in which "*"s act as wildcards. Will conform on match.
A vector or set of regex patterns or strs/kws/syms. Will conform on ANY match. If you need literal "*"s, use #"*" regex instead.
{:allow <spec> :deny <spec>} with specs as above.
Will conform iff allow
spec matches AND deny
spec does NOT.
Resulting conform fn is useful as allowlist and/or denylist. Example inputs: namespace strings, class names, ids, etc.
Spec examples: #{}, "", "foo.bar", "foo.bar.", #{"foo" "bar."}, {:allow #{"foo" "bar."} :deny #{"foo..bar."}}, #"(foo1|foo2).bar".
Given filter `spec`, returns a compiled (fn conform? [name]) that takes any nameable type (string, keyword, symbol). Spec may be: - A regex pattern. Will conform on match. - A str/kw/sym, in which "*"s act as wildcards. Will conform on match. - A vector or set of regex patterns or strs/kws/syms. Will conform on ANY match. If you need literal "*"s, use #"\*" regex instead. - {:allow <spec> :deny <spec>} with specs as above. Will conform iff `allow` spec matches AND `deny` spec does NOT. Resulting conform fn is useful as allowlist and/or denylist. Example inputs: namespace strings, class names, ids, etc. Spec examples: #{}, "*", "foo.bar", "foo.bar.*", #{"foo" "bar.*"}, {:allow #{"foo" "bar.*"} :deny #{"foo.*.bar.*"}}, #"(foo1|foo2)\.bar".
(name-with-attrs sym args)
(name-with-attrs sym args attrs-merge)
Given a symbol and args, returns [<name-with-attrs-meta> <args> <attrs>]
with support for defn
style ?docstring
and ?attrs-map
.
Given a symbol and args, returns [<name-with-attrs-meta> <args> <attrs>] with support for `defn` style `?docstring` and `?attrs-map`.
(nameable? x)
(named? x)
(nanoid)
(nanoid len)
Returns a random "Nano ID" of given length, Ref. https://github.com/ai/nanoid.
Uses strong randomness when possible. See also uuid-str
, rand-id-fn
.
Returns a random "Nano ID" of given length, Ref. <https://github.com/ai/nanoid>. Uses strong randomness when possible. See also `uuid-str`, `rand-id-fn`.
(nat-float? x)
(nat-int? x)
(nat-num? x)
(nblank-str? x)
(nblank? x)
(neg-float? x)
(neg-int? x)
(neg-num? x)
(nempty-str? x)
(nested-merge & maps)
Like merge
but does nested merging.
Like `merge` but does nested merging.
(nested-merge-with f & maps)
Like merge-with
but does nested merging.
Like `merge-with` but does nested merging.
(new-object)
(nneg? x)
(nnil)
(nnil x)
(nnil x y)
(nnil x y z)
(nnil x y z & more)
Returns first non-nil arg, or nil.
Returns first non-nil arg, or nil.
(node-paths m)
(node-paths node-pred m)
(node-paths node-pred m basis)
(norm-str s)
(norm-str form s)
Given a Unicode string, returns the normalized de/composed form. It's often a good idea to normalize strings before exchange or storage, especially if you're going to be querying against those string.
form
is ∈ #{:nfc :nfkc :nfd :nfkd <java.text.NormalizerForm>}.
Defaults to :nfc as per W3C recommendation.
Given a Unicode string, returns the normalized de/composed form. It's often a good idea to normalize strings before exchange or storage, especially if you're going to be querying against those string. `form` is ∈ #{:nfc :nfkc :nfd :nfkd <java.text.NormalizerForm>}. Defaults to :nfc as per W3C recommendation.
(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.
(normalize-headers rreq-or-rresp)
(now-dt)
Returns current system timestamp as java.util.Date
.
Returns current system timestamp as `java.util.Date`.
Returns current system timestamp as js/Date
.
Returns current system timestamp as `js/Date`.
(now-inst)
Returns current system timestamp as java.time.Instant
.
Returns current system timestamp as `java.time.Instant`.
Returns current system timestamp as js/Date
.
Returns current system timestamp as `js/Date`.
(now-nano)
Returns current value of best-resolution time source as nanoseconds.
Returns current value of best-resolution time source as nanoseconds.
(now-udt)
Returns current system timestamp as milliseconds since Unix epoch.
Returns current system timestamp as milliseconds since Unix epoch.
(nzero-num? x)
(oget k)
(oget o k)
(oget o k not-found)
Like get
for JS objects.
Like `get` for JS objects.
(oget-in ks)
(oget-in o ks)
(oget-in o ks not-found)
Like get-in
for JS objects.
Like `get-in` for JS objects.
(or-some)
(or-some x)
(or-some x & next)
Like or
, but returns the first non-nil form (may be falsey).
Like `or`, but returns the first non-nil form (may be falsey).
(oset-in o ks v)
Experimental. Like assoc-in
for JS objects.
Experimental. Like `assoc-in` for JS objects.
(parse-query-params s & [keywordize? encoding])
Based on ring-codec/form-decode
.
Based on `ring-codec/form-decode`.
(parse-version x)
(path & parts)
(perc n divisor)
(pnum-complement pnum)
(pnum? x)
Returns true iff given number in unsigned unit proportion interval ∈ℝ[0,1].
Returns true iff given number in unsigned unit proportion interval ∈ℝ[0,1].
(pool-executor {:keys [n-threads n-min-threads n-max-threads thread-name-prefix
daemon-threads? keep-alive-msecs queue-type queue-size]
:or {n-threads (+ 2 (get-num-threads [:ratio 1.0]))
thread-name-prefix "com.taoensso/encore-pool-"
daemon-threads? true
keep-alive-msecs 60000
queue-type :linked}})
Experimental, subject to change without notice!
Returns new java.util.concurrent.ThreadPoolExecutor
with given opts.
Experimental, subject to change without notice! Returns new `java.util.concurrent.ThreadPoolExecutor` with given opts.
(pos-float? x)
(pos-int? x)
(pos-num? x)
(pow n exp)
(pr-edn x)
(pr-edn _opts x)
Prints arg to an edn string readable with read-edn
.
Prints arg to an edn string readable with `read-edn`.
(pre-cache n-capacity f)
(pre-cache n-capacity fp-or-n-threads f)
Given a nullary fn f
that is non-idempotent and free of side effects,
returns a wrapped version of f
that asynchronously maintains a cache
of up to n-capacity
pre-computed return values of (f).
Useful when f
is expensive & may be called in a spikey fashion,
e.g. ideal for cryptographic key generators.
Given a nullary fn `f` that is non-idempotent and free of side effects, returns a wrapped version of `f` that asynchronously maintains a cache of up to `n-capacity` pre-computed return values of (f). Useful when `f` is expensive & may be called in a spikey fashion, e.g. ideal for cryptographic key generators.
(pred pred-fn)
Experimental, subject to change without notice!
Wraps given predicate fn to return Pred
for use with submap?
, etc.
Arity of predicate fn depends on context in which it'll be used.
See also pred-fn
.
Experimental, subject to change without notice! Wraps given predicate fn to return `Pred` for use with `submap?`, etc. Arity of predicate fn depends on context in which it'll be used. See also `pred-fn`.
(pred-fn pred)
Experimental, subject to change without notice!
Returns unwrapped predicate fn when given Pred
, otherwise returns nil.
See also pred
.
Experimental, subject to change without notice! Returns unwrapped predicate fn when given `Pred`, otherwise returns nil. See also `pred`.
(preserve-reduced rf)
Public version of core/preserving-reduced
.
Public version of `core/preserving-reduced`.
(print1 x)
Prints given argument as string, and flushes output stream.
Prints given argument as string, and flushes output stream.
(println-atomic x)
Like core/println
but won't interleave content from different threads.
Like `core/println` but won't interleave content from different threads.
(pull-val! atom_ k)
(pull-val! atom_ k not-found)
Removes and returns value mapped to key.
Removes and returns value mapped to key.
(qb spec form)
(qb spec form & more)
Simple util to benchmark/compare runtime of given form/s.
Runs sets of laps for each given form, recording the total runtime of each set. Returns the the total runtime in msecs of the fastest set of laps for each form.
(quick-bench [<num-sets> <num-laps>] <form1> <form2> <...>) => [<total runtime msecs of fastest set of laps for form1> <total runtime msecs of fastest set of laps for form2> <...>]
Total number of runs for each form is: num-sets
* num-laps
If omitted, the default num-sets
is 6 (to include warmup):
(quick-bench <num-laps> <form1> <form2> <...>)
Example (comparing runtime of first
and nth
against vector):
(let [v [:a]] (quick-bench 1e6 (first v) (nth v 0))) => [67.43 39.05]
Simple util to benchmark/compare runtime of given form/s. Runs sets of laps for each given form, recording the total runtime of each set. Returns the the total runtime in msecs of the fastest set of laps for each form. (quick-bench [<num-sets> <num-laps>] <form1> <form2> <...>) => [<total runtime msecs of fastest set of laps for form1> <total runtime msecs of fastest set of laps for form2> <...>] Total number of runs for each form is: `num-sets` * `num-laps` If omitted, the default `num-sets` is 6 (to include warmup): (quick-bench <num-laps> <form1> <form2> <...>) Example (comparing runtime of `first` and `nth` against vector): (let [v [:a]] (quick-bench 1e6 (first v) (nth v 0))) => [67.43 39.05]
(qualified-ident? x)
(qualified-keyword? x)
(qualified-symbol? x)
(queue)
(queue coll)
Returns a new PersistentQueue
.
Returns a new `PersistentQueue`.
(queue* & items)
Returns a new PersistentQueue
given items.
Returns a new `PersistentQueue` given items.
(queue? x)
Returns true iff given a PersistentQueue
.
Returns true iff given a `PersistentQueue`.
(quick-bench spec form)
(quick-bench spec form & more)
Simple util to benchmark/compare runtime of given form/s.
Runs sets of laps for each given form, recording the total runtime of each set. Returns the the total runtime in msecs of the fastest set of laps for each form.
(quick-bench [<num-sets> <num-laps>] <form1> <form2> <...>) => [<total runtime msecs of fastest set of laps for form1> <total runtime msecs of fastest set of laps for form2> <...>]
Total number of runs for each form is: num-sets
* num-laps
If omitted, the default num-sets
is 6 (to include warmup):
(quick-bench <num-laps> <form1> <form2> <...>)
Example (comparing runtime of first
and nth
against vector):
(let [v [:a]] (quick-bench 1e6 (first v) (nth v 0))) => [67.43 39.05]
Simple util to benchmark/compare runtime of given form/s. Runs sets of laps for each given form, recording the total runtime of each set. Returns the the total runtime in msecs of the fastest set of laps for each form. (quick-bench [<num-sets> <num-laps>] <form1> <form2> <...>) => [<total runtime msecs of fastest set of laps for form1> <total runtime msecs of fastest set of laps for form2> <...>] Total number of runs for each form is: `num-sets` * `num-laps` If omitted, the default `num-sets` is 6 (to include warmup): (quick-bench <num-laps> <form1> <form2> <...>) Example (comparing runtime of `first` and `nth` against vector): (let [v [:a]] (quick-bench 1e6 (first v) (nth v 0))) => [67.43 39.05]
(rand-id-fn {:keys [chars len rand-bytes-fn]
:or {chars :nanoid len 21 rand-bytes-fn secure-rand-bytes}})
Returns a (fn rand-id []) that returns random id strings. Uses strong randomness when possible.
Options include:
:chars
- ∈ #{<string> :nanoid :alphanumeric :no-look-alikes ...}
:len
- Length of id strings to generate
:rand-bytes-fn
- Optional (fn [size]) to return random byte array of given size
See also uuid-str
, nano-id
.
Returns a (fn rand-id []) that returns random id strings. Uses strong randomness when possible. Options include: `:chars` - ∈ #{<string> :nanoid :alphanumeric :no-look-alikes ...} `:len` - Length of id strings to generate `:rand-bytes-fn` - Optional (fn [size]) to return random byte array of given size See also `uuid-str`, `nano-id`.
(rate-limiter spec)
(rate-limiter opts spec)
Takes a map spec of form {<limit-id> [<n-max-reqs> <msecs-window>]}, and returns a basic stateful (fn rate-limiter [req-id] [command req-id]).
Call fn with a single request id (e.g. username) by which to count/limit. Will return:
Or call fn with an additional command argument:
:rl/peek
<req-id> - Check limits w/o incrementing count.
:rl/reset
<req-id> - Reset all limits for given req-id.
Example:
(defonce my-rate-limiter (rate-limiter {"1 per sec" [1 1000] "10 per min" [10 60000]}))
(defn send-message! [username msg-content] (if-let [fail (my-rate-limiter username)] (throw (ex-info "Sorry, rate limited!" {:fail fail})) <send message>))
Takes a map spec of form {<limit-id> [<n-max-reqs> <msecs-window>]}, and returns a basic stateful (fn rate-limiter [req-id] [command req-id]). Call fn with a single request id (e.g. username) by which to count/limit. Will return: - nil when all limits pass for that id, or - [<worst-limit-id> <worst-backoff-msecs> {<limit-id> <backoff-msecs>}] when any limits fail for that id. Or call fn with an additional command argument: `:rl/peek` <req-id> - Check limits w/o incrementing count. `:rl/reset` <req-id> - Reset all limits for given req-id. Example: (defonce my-rate-limiter (rate-limiter {"1 per sec" [1 1000] "10 per min" [10 60000]})) (defn send-message! [username msg-content] (if-let [fail (my-rate-limiter username)] (throw (ex-info "Sorry, rate limited!" {:fail fail})) <send message>))
(re-pattern? x)
(read-edn s)
(read-edn opts s)
Attempts to pave over differences in:
clojure.edn/read-string
, clojure.tools.edn/read-string
,
cljs.reader/read-string
, cljs.tools.reader/read-string
.
cljs.reader
in particular can be a pain.
Attempts to pave over differences in: `clojure.edn/read-string`, `clojure.tools.edn/read-string`, `cljs.reader/read-string`, `cljs.tools.reader/read-string`. `cljs.reader` in particular can be a pain.
(reduce-indexed rf init coll)
Like reduce
but takes (rf [acc idx in]) with idx as in map-indexed
.
As reduce-kv
against vector coll, but works on any seqable coll type.
Like `reduce` but takes (rf [acc idx in]) with idx as in `map-indexed`. As `reduce-kv` against vector coll, but works on any seqable coll type.
(reduce-interleave-all rf init colls)
Reduces sequence of elements interleaved from given colls
.
(reduce-interleave-all conj [] [[:a :b] [1 2 3]]) => [:a 1 :b 2 3]
Reduces sequence of elements interleaved from given `colls`. (reduce-interleave-all conj [] [[:a :b] [1 2 3]]) => [:a 1 :b 2 3]
(reduce-kvs rf init kvs)
Like reduce-kv
but takes a flat sequence of kv pairs.
Like `reduce-kv` but takes a flat sequence of kv pairs.
(reduce-multi rf init coll)
(reduce-multi rf1 init1 rf2 init2 coll)
(reduce-multi rf1 init1 rf2 init2 rf3 init3 coll)
Like reduce
but supports separate simultaneous accumulators
as a micro-optimisation when reducing a large collection multiple
times.
Like `reduce` but supports separate simultaneous accumulators as a micro-optimisation when reducing a large collection multiple times.
(reduce-n rf init end)
(reduce-n rf init start end)
(reduce-n rf init start end step)
(reduce-obj f init o)
Like reduce-kv
but for JavaScript objects.
Like `reduce-kv` but for JavaScript objects.
(reduce-top n rf init coll)
(reduce-top n keyfn rf init coll)
(reduce-top n keyfn cmp rf init coll)
Reduces the top n
items from coll
of N items.
Clj impln is O(N.logn) vs O(N.logN) for (take n (sort-by ...)).
Reduces the top `n` items from `coll` of N items. Clj impln is O(N.logn) vs O(N.logN) for (take n (sort-by ...)).
(reduce-zip rf init xs ys)
Reduces given sequential xs and ys as pairs (e.g. key-val pairs). Calls (rf acc x y) for each sequential pair.
Useful, among other things, as a more flexible version of zipmap
.
Reduces given sequential xs and ys as pairs (e.g. key-val pairs). Calls (rf acc x y) for each sequential pair. Useful, among other things, as a more flexible version of `zipmap`.
(remove-keys pred m)
(remove-vals pred m)
(rename-keys replacements m)
Returns a map like the one given, replacing keys using given {<old-new> <new-key>} replacements. O(min(n_replacements, n_m)).
Returns a map like the one given, replacing keys using given {<old-new> <new-key>} replacements. O(min(n_replacements, n_m)).
(repeatedly-into coll n f)
Like repeatedly
but faster and conj
s items into given collection.
Like `repeatedly` but faster and `conj`s items into given collection.
(require-telemere-if-present)
Experimental, subject to change without notice! Requires Telemere if it's present, otherwise noops. For Cljs: needs ClojureScript >= v1.9.293, and must be placed at top of file.
Experimental, subject to change without notice! Requires Telemere if it's present, otherwise noops. For Cljs: needs ClojureScript >= v1.9.293, and must be placed at top of file.
(reset!? atom_ val)
Atomically swaps value of atom_
to val
and returns
true iff the atom's value changed. See also reset-in!?
.
Atomically swaps value of `atom_` to `val` and returns true iff the atom's value changed. See also `reset-in!?`.
(reset-in! atom_ val)
(reset-in! atom_ ks val)
(reset-in! atom_ ks not-found val)
Like reset!
but supports update-in
semantics, returns <old-key-val>.
Like `reset!` but supports `update-in` semantics, returns <old-key-val>.
(reset-in!? atom_ val)
(reset-in!? atom_ ks val)
(reset-in!? atom_ ks not-found val)
Like reset-in!
but returns true iff the atom's value changed.
Like `reset-in!` but returns true iff the atom's value changed.
(reset-val! atom_ k val)
(reset-val! atom_ k not-found val)
Like reset-in!
but optimized for single-key case.
Like `reset-in!` but optimized for single-key case.
(reset-val!? atom_ k new-val)
Like reset-in!?
but optimized for single-key case.
Like `reset-in!?` but optimized for single-key case.
(resolve-sym sym)
(resolve-sym macro-env sym)
(resolve-sym macro-env sym may-require-ns?)
Returns resolved qualified Clj/s symbol, or nil.
Returns resolved qualified Clj/s symbol, or nil.
(revery-kv? pred coll)
(revery? pred coll)
(revery? xform pred coll)
(rfirst pred coll)
(rfirst xform pred coll)
(rfirst-kv pred coll)
(ring-default-headers headers rresp)
(ring-merge-headers headers rresp)
(ring-redirect-resp url)
(ring-redirect-resp kind url)
(ring-redirect-resp kind url flash)
(ring-resp-map x)
(ring-set-body body rresp)
(ring-set-headers headers rresp)
(ring-set-status code rresp)
(rnum? x)
Returns true iff given number in signed unit proportion interval ∈ℝ[-1,1].
Returns true iff given number in signed unit proportion interval ∈ℝ[-1,1].
(rolling-counter msecs)
Experimental. Returns a RollingCounter that you can:
msecs
window and return RollingCounter.msecs
window.Experimental. Returns a RollingCounter that you can: - Invoke to increment count in last `msecs` window and return RollingCounter. - Deref to return count in last `msecs` window.
(rolling-list nmax)
(rolling-list nmax {:keys [init-val]})
Returns a stateful fn of 2 arities:
(fn [ ]) => Returns current array in O(n).
(fn [x]) => Adds x
to right of list, maintaining length <~ nmax
.
Returns nil. Very fast (faster than rolling-vector
).
Useful for maintaining limited-length histories, etc.
See also rolling-vector
.
Returns a stateful fn of 2 arities: (fn [ ]) => Returns current array in O(n). (fn [x]) => Adds `x` to right of list, maintaining length <~ `nmax`. Returns nil. Very fast (faster than `rolling-vector`). Useful for maintaining limited-length histories, etc. See also `rolling-vector`.
(rolling-vector nmax)
(rolling-vector nmax {:keys [gc-every init-val] :or {gc-every 16000.0}})
Returns a stateful fn of 2 arities:
(fn [ ]) => Returns current sub/vector in O(1).
(fn [x]) => Adds x
to right of sub/vector, maintaining length <= nmax
.
Returns current sub/vector.
Useful for maintaining limited-length histories, etc.
See also rolling-list
(Clj only).
Returns a stateful fn of 2 arities: (fn [ ]) => Returns current sub/vector in O(1). (fn [x]) => Adds `x` to right of sub/vector, maintaining length <= `nmax`. Returns current sub/vector. Useful for maintaining limited-length histories, etc. See also `rolling-list` (Clj only).
(round* n)
(round* kind n)
(round* kind precision n)
(round0 n)
(round1 n)
(round2 n)
(roundn precision n)
(rsome pred coll)
(rsome xform pred coll)
(rsome-kv pred coll)
(run! proc coll)
(run-kv! proc m)
(run-kvs! proc kvs)
(run-obj! proc obj)
(runner {:keys [mode buffer-size n-threads thread-name daemon-threads?]
:as opts
:or {mode :dropping buffer-size 1024 n-threads 1}})
Experimental, subject to change without notice!! Returns a new stateful (fn runner ([]) ([f])) such that: (runner f) => Runner should execute given nullary fn according to runner opts. Returns: nil if runner has stopped accepting new execution requests. true if fn was accepted for execution without back pressure. false if runner's back-pressure mechanism was engaged.
(runner) => Runner should stop accepting new execution requests. Returns true iff runner's status changed with this call.
Compared to agents:
These properties make them useful as configurable async workers, etc.
Options include:
mode
- Mode of operation, ∈ #{:sync :blocking :dropping :sliding}.
buffer-size
- Size of buffer before back-pressure mechanism is engaged.
n-threads
- Number of threads for asynchronously executing fns.
NB execution order may be non-sequential when n > 1.
Experimental, subject to change without notice!! Returns a new stateful (fn runner ([]) ([f])) such that: (runner f) => Runner should execute given nullary fn according to runner opts. Returns: nil if runner has stopped accepting new execution requests. true if fn was accepted for execution *without* back pressure. false if runner's back-pressure mechanism was engaged. (runner) => Runner should stop accepting new execution requests. Returns true iff runner's status changed with this call. Compared to agents: - Runners have (configurable) back pressure. - Runners may be non-linear when n-threads > 1. - Runners take nullary fns rather than unary fns of state. - Runners have no validators or watches. - Runners auto shutdown their threads on JVM shutdown. These properties make them useful as configurable async workers, etc. Options include: `mode` - Mode of operation, ∈ #{:sync :blocking :dropping :sliding}. `buffer-size` - Size of buffer before back-pressure mechanism is engaged. `n-threads` - Number of threads for asynchronously executing fns. NB execution order may be non-sequential when n > 1.
(satisfies! protocol arg)
(satisfies! protocol arg {:keys [msg context param ...]})
(satisfies! protocol arg & {:keys [msg context param ...]})
If (satisfies? protocol arg) is true, returns arg.
Otherwise throws runtime ExceptionInfo
with unexpected-arg!
.
See unexpected-arg!
for more info.
If (satisfies? protocol arg) is true, returns arg. Otherwise throws runtime `ExceptionInfo` with `unexpected-arg!`. See `unexpected-arg!` for more info.
(satisfies? protocol x)
Faster satisfies?
to work around CLJ-1814 until a proper upstream fix.
May cache, so possibly inappropriate for dynamic work.
Faster `satisfies?` to work around CLJ-1814 until a proper upstream fix. May cache, so possibly inappropriate for dynamic work.
(sayf fmt & xs)
(sayp & xs)
(sb-append str-builder s)
(sb-append str-builder s & more)
Appends given string to given string builder. See also str-builder.
Appends given string to given string builder. See also `str-builder.`
(secs opts)
(secs & {:as opts :keys [years months weeks days hours mins secs msecs ms]})
Returns ~number of seconds in period defined by given args.
Returns ~number of seconds in period defined by given args.
(secs->ms secs)
(secure-rand-bytes size)
Returns a random byte array of given size. Uses strong randomness when possible.
Returns a random byte array of given size. Uses strong randomness when possible.
(secure-rng)
Returns a an auto-reseeding thread-local java.security.SecureRandom
.
Favours security over performance. May block while waiting on entropy!
Returns a an auto-reseeding thread-local `java.security.SecureRandom`. Favours security over performance. May block while waiting on entropy!
(secure-rng-mock!!! long-seed)
Returns INSECURE java.security.SecureRandom
mock instance backed by
a seeded deterministic java.util.Random
. Useful for testing, etc.
Returns **INSECURE** `java.security.SecureRandom` mock instance backed by a seeded deterministic `java.util.Random`. Useful for testing, etc.
(select-nested-keys src-map key-spec)
Like select-keys
but supports nested key spec:
(select-nested-keys
{:a :A :b :B :c {:c1 :C1 :c2 :C2} :d :D} ; src-map
[:a {:c [:c1], :d [:d1 :d2]}]) ; key-spec
=> {:a :A, :c {:c1 :C1}, :d :D}
Note that as with the {:d [:d1 :d2]}
spec in the example above,
if spec expects a nested map but the actual value is not a map,
the actual value will be included in output as-is.
Has the same behaviour as select-keys
when key-spec
is a
simple vector of keys.
Like `select-keys` but supports nested key spec: (select-nested-keys {:a :A :b :B :c {:c1 :C1 :c2 :C2} :d :D} ; `src-map` [:a {:c [:c1], :d [:d1 :d2]}]) ; `key-spec` => {:a :A, :c {:c1 :C1}, :d :D} Note that as with the `{:d [:d1 :d2]}` spec in the example above, if spec expects a nested map but the actual value is not a map, the actual value will be included in output as-is. Has the same behaviour as `select-keys` when `key-spec` is a simple vector of keys.
(session-swap rreq rresp f & args)
Util to help correctly update Ring sessions (something easy to get wrong!).
Given a Ring request (rreq) and Ring response (rresp), returns a new Ring response with the response session updated to be (f <old-session>) or (apply f <old-session> args).
Util to help correctly update Ring sessions (something easy to get wrong!). Given a Ring request (rreq) and Ring response (rresp), returns a new Ring response with the response session updated to be (f <old-session>) or (apply f <old-session> args).
(set-var-root! var-sym root-value)
Sets root binding (balue) of the var identified by given symbol, and returns
the new value. Cross-platform. See also update-var-root!
.
Sets root binding (balue) of the var identified by given symbol, and returns the new value. Cross-platform. See also `update-var-root!`.
(signal! {:as opts
:keys [elidable? location timestamp uid middleware sample ns kind id
level filter when rate-limit ctx parent trace? let data msg
error run & user-opts]})
Experimental, subject to change without notice! If Telemere is present, expands to Telemere signal call and returns true. Otherwise noops and returns false.
NB: must be used with require-telemere-if-present
!
Example usage:
(ns my-ns (:require [taoensso.encore :as enc]))
(enc/require-telemere-if-present) ; At top of file, just below ns
form
;; Later in your code...
(or (enc/signal! {<signal-opts>}) ; Expands to Telemere signal call (println "Println fallback!") ; Fallback if Telemere not present )
For info on signal options, see Telemere documentation [1] or
taoensso.telemere/signal!
docstring [2].
[1] Ref. https://github.com/taoensso/telemere#documentation [2] Ref. https://taoensso.github.io/telemere/taoensso.telemere.html#var-signal.21
Experimental, subject to change without notice! If Telemere is present, expands to Telemere signal call and returns true. Otherwise noops and returns false. NB: *must* be used with `require-telemere-if-present`! Example usage: (ns my-ns (:require [taoensso.encore :as enc])) (enc/require-telemere-if-present) ; At top of file, just below `ns` form ;; Later in your code... (or (enc/signal! {<signal-opts>}) ; Expands to Telemere signal call (println "Println fallback!") ; Fallback if Telemere not present ) For info on signal options, see Telemere documentation [1] or `taoensso.telemere/signal!` docstring [2]. [1] Ref. <https://github.com/taoensso/telemere#documentation> [2] Ref. <https://taoensso.github.io/telemere/taoensso.telemere.html#var-signal.21>
(simple-date-format pattern & [{:keys [locale timezone] :as opts}])
Returns a thread-local java.text.SimpleDateFormat
.
Returns a thread-local `java.text.SimpleDateFormat`.
(simple-date-format* pattern locale timezone)
(simple-ident? x)
(simple-keyword? x)
(simple-symbol? x)
Like slurp-resource
but caches slurps against file's last-modified udt.
Like `slurp-resource` but caches slurps against file's last-modified udt.
(slurp-resource rname)
Returns slurped named resource on classpath, or nil when resource not found.
Returns slurped named resource on classpath, or nil when resource not found.
(some= x y)
(some= x y & more)
(some? x)
(sortv coll)
(sortv comparator coll)
(sortv ?keyfn comparator coll)
Like core/sort
but:
comparator
can be :asc
, :desc
, or an arbitrary comparator.keyfn
may be provided, as in core/sort-by
.Like `core/sort` but: - Returns a vector. - `comparator` can be `:asc`, `:desc`, or an arbitrary comparator. - An optional `keyfn` may be provided, as in `core/sort-by`.
(str->utf8-ba s)
(str-?index s substr)
(str-?index s substr start-idx)
(str-?index s substr start-idx last?)
Returns (first/last) ?index of substring if it exists within given string.
Returns (first/last) ?index of substring if it exists within given string.
(str-builder)
(str-builder init-str)
Returns a new stateful string builder:
java.lang.StringBuilder
for Cljgoog.string.StringBuffer
for CljsSee also sb-append
.
Returns a new stateful string builder: - `java.lang.StringBuilder` for Clj - `goog.string.StringBuffer` for Cljs See also `sb-append`.
(str-builder? x)
(str-contains? s substr)
(str-ends-with? s substr)
(str-join coll)
(str-join separator coll)
(str-join separator xform coll)
Faster, transducer-based generalization of clojure.string/join
with xform
support.
Faster, transducer-based generalization of `clojure.string/join` with `xform` support.
(str-join-once separator coll)
Like string/join
but skips nils and duplicate separators.
Like `string/join` but skips nils and duplicate separators.
(str-replace s match replacement)
Like str/replace
but provides consistent clj/s behaviour.
Workaround for http://dev.clojure.org/jira/browse/CLJS-794, http://dev.clojure.org/jira/browse/CLJS-911.
Note that ClojureScript 1.7.145 introduced a partial fix for CLJS-911. A full fix could unfortunately not be introduced w/o breaking compatibility with the previously incorrect behaviour. CLJS-794 also remains unresolved.
Like `str/replace` but provides consistent clj/s behaviour. Workaround for <http://dev.clojure.org/jira/browse/CLJS-794>, <http://dev.clojure.org/jira/browse/CLJS-911>. Note that ClojureScript 1.7.145 introduced a partial fix for CLJS-911. A full fix could unfortunately not be introduced w/o breaking compatibility with the previously incorrect behaviour. CLJS-794 also remains unresolved.
(str-rf)
(str-rf acc)
(str-rf acc in)
String builder reducing fn.
String builder reducing fn.
(str-starts-with? s substr)
(stringy? x)
(submap? m sub)
Returns true iff sub
is a (possibly nested) submap of m
,
i.e. iff every (nested) value in sub
has the same (nested) value in m
.
Uses stack recursion so supports only limited nesting.
Returns true iff `sub` is a (possibly nested) submap of `m`, i.e. iff every (nested) value in `sub` has the same (nested) value in `m`. Uses stack recursion so supports only limited nesting.
(swap-in! atom_ f)
(swap-in! atom_ ks f)
(swap-in! atom_ ks not-found f)
Like swap!
but supports update-in
semantics,
returns <new-key-val> or <swapped-return-val>.
Like `swap!` but supports `update-in` semantics, returns <new-key-val> or <swapped-return-val>.
(swap-val! atom_ k f)
(swap-val! atom_ k not-found f)
Like swap-in!
but optimized for single-key case.
Like `swap-in!` but optimized for single-key case.
(swapped new-val return-val)
(swapped-vec x)
(swapped? x)
(takev n coll)
(test-fixtures fixtures-map)
Given a {:before ?(fn []) :after ?(fn [])} map, returns cross-platform
test fixtures for use by both clojure.test
and cljs.test
:
(let [f (test-fixtures {:before (fn [] (test-setup))})] (clojure.test/use-fixtures :once f) (cljs.test/use-fixtures :once f))
Given a {:before ?(fn []) :after ?(fn [])} map, returns cross-platform test fixtures for use by both `clojure.test` and `cljs.test`: (let [f (test-fixtures {:before (fn [] (test-setup))})] (clojure.test/use-fixtures :once f) (cljs.test/use-fixtures :once f))
(thread-local & body)
Given a body that returns an initial value for the current thread,
returns a ThreadLocal
proxy that can be derefed to get the current
thread's current value.
Commonly used to achieve thread safety during Java interop.
In the common case, body
will be a call to some Java constructor
that returns a non-thread-safe instance.
Example:
(def thread-local-simple-date-format_
"Deref to return a thread-local SimpleDateFormat
"
(thread-local (SimpleDateFormat. "yyyy-MM-dd")))
(.format @thread-local-simple-date-format_ (Date.)) => "2023-01-24"
NB: don't pass the derefed value to other threads!
Given a body that returns an initial value for the current thread, returns a `ThreadLocal` proxy that can be derefed to get the current thread's current value. Commonly used to achieve thread safety during Java interop. In the common case, `body` will be a call to some Java constructor that returns a non-thread-safe instance. Example: (def thread-local-simple-date-format_ "Deref to return a thread-local `SimpleDateFormat`" (thread-local (SimpleDateFormat. "yyyy-MM-dd"))) (.format @thread-local-simple-date-format_ (Date.)) => "2023-01-24" NB: don't pass the derefed value to other threads!
(thread-local* init-val-fn)
Low-level, see thread-local
instead.
Low-level, see `thread-local` instead.
(thread-local-proxy & body)
Low-level, see thread-local
instead.
Low-level, see `thread-local` instead.
(throwable? x)
(throws form)
(throws err-type form)
(throws err-type err-pattern form)
Evals form
and if it throws an error that matches given criteria using
matching-error
, returns the matching error. Otherwise returns nil.
See also matching-error
, throws?
.
Evals `form` and if it throws an error that matches given criteria using `matching-error`, returns the matching error. Otherwise returns nil. See also `matching-error`, `throws?`.
(throws? form)
(throws? err-type form)
(throws? err-type err-pattern form)
Evals form
and if it throws an error that matches given criteria using
matching-error
, returns true. Otherwise returns false.
Useful for unit tests, e.g.: (is (throws? {:a :b} (throw (ex-info "Test" {:a :b :c :d}))))
See also matching-error
, throws
.
Evals `form` and if it throws an error that matches given criteria using `matching-error`, returns true. Otherwise returns false. Useful for unit tests, e.g.: (is (throws? {:a :b} (throw (ex-info "Test" {:a :b :c :d})))) See also `matching-error`, `throws`.
(time-ms & body)
Returns number of milliseconds it took to execute body.
Returns number of milliseconds it took to execute body.
(time-ns & body)
Returns number of nanoseconds it took to execute body.
Returns number of nanoseconds it took to execute body.
(timeout-future? x)
(top n coll)
(top n keyfn coll)
(top n keyfn cmp coll)
Returns a sorted vector of the top n
items from coll
using reduce-top
.
Returns a sorted vector of the top `n` items from `coll` using `reduce-top`.
(top-into to n coll)
(top-into to n keyfn coll)
(top-into to n keyfn cmp coll)
Conjoins the top n
items from coll
into to
using reduce-top
.
Conjoins the top `n` items from `coll` into `to` using `reduce-top`.
(transient? x)
(try* expr catch-clause-or-clauses ?finally-clause)
Like try
, but catch
clause classnames can be the special keywords
:any
or :common
for cross-platform catching. Addresses CLJ-1293.
Like `try`, but `catch` clause classnames can be the special keywords `:any` or `:common` for cross-platform catching. Addresses CLJ-1293.
(try-eval form)
If form
can be successfully evaluated at macro-expansion time, expands to form
.
Otherwise expands to nil
.
If `form` can be successfully evaluated at macro-expansion time, expands to `form`. Otherwise expands to `nil`.
(udt? x)
(unexpected-arg! arg)
(unexpected-arg! arg {:keys [msg context param expected ...]})
(unexpected-arg! arg & {:keys [msg context param expected ...]})
Throws runtime ExceptionInfo
to indicate an unexpected argument.
Takes optional kvs for merging into exception's data map.
(let [mode :unexpected] (case mode :read (do <...>) :write (do <...>) (unexpected-arg! mode :context `my-function :param 'mode :expected #{:read :write}))) =>
Unexpected argument: :unexpected {:arg {:value :unexpected, :type clojure.lang.Keyword}, :context 'taoensso.encore/my-function :param 'mode :expected #{:read :write}}
Throws runtime `ExceptionInfo` to indicate an unexpected argument. Takes optional kvs for merging into exception's data map. (let [mode :unexpected] (case mode :read (do <...>) :write (do <...>) (unexpected-arg! mode :context `my-function :param 'mode :expected #{:read :write}))) => Unexpected argument: :unexpected {:arg {:value :unexpected, :type clojure.lang.Keyword}, :context 'taoensso.encore/my-function :param 'mode :expected #{:read :write}}
(update-in m ks f)
(update-in m ks not-found f)
Like core/update-in
but:.
not-found
.:update/dissoc
, :update/abort
.Like `core/update-in` but:. - Empty ks will return (f m), not act like [nil] ks. - Adds support for `not-found`. - Adds support for special return vals: `:update/dissoc`, `:update/abort`.
(update-var-root! var-sym update-fn)
Updates root binding (value) of the var identified by given symbol, and returns
the new value. Similar to alter-var-root
but cross-platform and takes a symbol
rather than a var. See also set-var-root!
.
Updates root binding (value) of the var identified by given symbol, and returns the new value. Similar to `alter-var-root` but cross-platform and takes a symbol rather than a var. See also `set-var-root!`.
(uri? x)
(url-decode s & [encoding])
Stolen from http://goo.gl/99NSR1.
Stolen from <http://goo.gl/99NSR1>.
(url-encode s & [encoding])
(url-encode s)
Based on https://goo.gl/fBqy6e.
Based on <https://goo.gl/fBqy6e>.
(utf8-ba->str ba)
(uuid)
For Clj: returns a random java.util.UUID
.
For Cljs: returns a random UUID string.
Uses strong randomness when possible.
See also uuid-str
, nanoid
, rand-id-fn
.
For Clj: returns a random `java.util.UUID`. For Cljs: returns a random UUID string. Uses strong randomness when possible. See also `uuid-str`, `nanoid`, `rand-id-fn`.
(uuid-str)
(uuid-str max-len)
Returns a random UUID string of given length (max 36).
Uses strong randomness when possible. See also uuid
, nanoid
, rand-id-fn
.
Returns a random UUID string of given length (max 36). Uses strong randomness when possible. See also `uuid`, `nanoid`, `rand-id-fn`.
(vec2? x)
(vec3? x)
(vinterleave-all colls)
(vinterleave-all c1 c2)
(vinterleave-all c1 c2 c3)
(vinterleave-all c1 c2 c3 & colls)
Like interleave
, but:
Single-arity version takes a coll of colls.
Like `interleave`, but: - Returns a vector rather than lazy seq (=> greedy). - Includes all items (i.e. stops when the longest rather than shortest coll has been consumed). Single-arity version takes a coll of colls.
(virtual-executor)
Experimental, subject to change without notice!
Returns new virtual java.util.concurrent.ThreadPerTaskExecutor
when
possible (JVM 21+), otherwise returns nil.
Experimental, subject to change without notice! Returns new virtual `java.util.concurrent.ThreadPerTaskExecutor` when possible (JVM 21+), otherwise returns nil.
(vnext v)
(vrest v)
(vsplit-first v)
(vsplit-last v)
(when test-or-bindings & body)
Like core/when
but acts like when-let
when given a binding vector
as test expr.
Like `core/when` but acts like `when-let` when given a binding vector as test expr.
(when-let bindings & body)
Like core/when-let
but can bind multiple values for body
iff all tests
are truthy, supports internal unconditional :let
s.
Like `core/when-let` but can bind multiple values for `body` iff all tests are truthy, supports internal unconditional `:let`s.
(when-not test-or-bindings & body)
Like core/when-not
but acts like when-let
when given a binding vector
as test expr.
Like `core/when-not` but acts like `when-let` when given a binding vector as test expr.
(when-some test-or-bindings & body)
(when? pred x)
(with-dynamic-assertion-data data & body)
Prefer with-data
Prefer `with-data`
(with-truss-data data & body)
Executes body with dynamic assertion data bound to given value. This data will be included in any violation errors thrown by body.
Executes body with dynamic assertion data bound to given value. This data will be included in any violation errors thrown by body.
(without-meta x)
(xdistinct)
(xdistinct keyfn)
(zero-num? x)
cljdoc is a website building & hosting documentation for Clojure/Script libraries
× close