-
-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathencore.cljx
1636 lines (1405 loc) · 59.9 KB
/
encore.cljx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(ns taoensso.encore
"The utils you want, in the package you deserve™.
Subset of the commonest Ensso utils w/o external dependencies."
{:author "Peter Taoussanis"}
#+clj (:refer-clojure :exclude [format])
#+clj (:require [clojure.string :as str]
[clojure.set :as set]
[clojure.java.io :as io]
;; [clojure.core.async :as async]
[clojure.tools.reader.edn :as edn])
;; #+clj (:import [org.apache.commons.codec.binary Base64])
#+clj (:import [java.util Date Locale TimeZone]
[java.text SimpleDateFormat])
;;;
#+cljs (:require [clojure.string :as str]
[clojure.set :as set]
;; [cljs.core.async :as async]
[cljs.reader :as edn]
;;[goog.crypt.base64 :as base64]
[goog.string :as gstr]
[goog.string.format]
[goog.string.StringBuffer]
[goog.events :as gevents]
[goog.net.XhrIo :as gxhr]
[goog.net.XhrIoPool :as gxhr-pool]
;; [goog.net.XhrManager :as xhrm]
[goog.Uri.QueryData :as gquery-data]
[goog.structs :as gstructs]
[goog.net.EventType]
[goog.net.ErrorCode])
#+cljs (:require-macros [taoensso.encore :as encore-macros]))
;;;; Core
(defmacro ^:also-cljs if-cljs
"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,
https://groups.google.com/d/msg/clojurescript/iBY5HaQda4A/w1lAQi9_AwsJ."
[then else]
(if (:ns &env) ; nil in Clojure, nnil in ClojureScript
then else))
(defn name-with-attrs
"Stolen from `clojure.tools.macro`.
Handles optional docstrings & attr maps for a macro def's name."
[name macro-args]
(let [[docstring macro-args] (if (string? (first macro-args))
[(first macro-args) (next macro-args)]
[nil macro-args])
[attr macro-args] (if (map? (first macro-args))
[(first macro-args) (next macro-args)]
[{} macro-args])
attr (if docstring (assoc attr :doc docstring) attr)
attr (if (meta name) (conj (meta name) attr) attr)]
[(with-meta name attr) macro-args]))
(defmacro ^:also-cljs defonce*
"Like `clojure.core/defonce` but supports optional docstring and attributes
map for name symbol."
{:arglists '([name expr])}
[name & sigs]
(let [[name [expr]] (name-with-attrs name sigs)]
`(clojure.core/defonce ~name ~expr)))
(defmacro declare-remote
"Declares the given ns-qualified names, preserving symbol metadata. Useful for
circular dependencies."
[& names]
(let [original-ns (str *ns*)]
`(do ~@(map (fn [n]
(let [ns (namespace n)
v (name n)
m (meta n)]
`(do (in-ns '~(symbol ns))
(declare ~(with-meta (symbol v) m))))) names)
(in-ns '~(symbol original-ns)))))
(defmacro defalias
"Defines an alias for a var, preserving metadata. Adapted from
clojure.contrib/def.clj, Ref. http://goo.gl/xpjeH"
[name target & [doc]]
`(let [^clojure.lang.Var v# (var ~target)]
(alter-meta! (def ~name (.getRawRoot v#))
#(merge % (apply dissoc (meta v#) [:column :line :file :test :name])
(when-let [doc# ~doc] {:doc doc#})))
(var ~name)))
(defmacro ^:also-cljs cond-throw
"Like `cond` but throws on no-match like `case`, `condp`."
[& clauses] `(cond ~@clauses :else (throw (ex-info "No matching clause" {}))))
(comment (cond false "false") (cond-throw false "false"))
(defmacro doto-cond "Diabolical cross between `doto`, `cond->` and `as->`."
[[name x] & clauses]
(assert (even? (count clauses)))
(let [g (gensym)
pstep (fn [[test-expr step]] `(when-let [~name ~test-expr]
(-> ~g ~step)))]
`(let [~g ~x]
~@(map pstep (partition 2 clauses))
~g)))
(defmacro ^:also-cljs case-eval
"Like `case` but evaluates test constants for their compile-time value."
[e & clauses]
(let [;; Don't evaluate default expression!
default (when (odd? (count clauses)) (last clauses))
clauses (if default (butlast clauses) clauses)]
`(case ~e
~@(map-indexed (fn [i# form#] (if (even? i#) (eval form#) form#))
clauses)
~(when default default))))
(defmacro ^:also-cljs if-lets
"Like `if-let` but binds multiple values iff all tests are true."
([bindings then] `(if-lets ~bindings ~then nil))
([bindings then else]
(let [[b1 b2 & bnext] bindings]
(if bnext
`(if-let [~b1 ~b2] (if-lets ~(vec bnext) ~then ~else) ~else)
`(if-let [~b1 ~b2] ~then ~else)))))
(comment (if-lets [a :a] a)
(if-lets [a nil] a)
(if-lets [a :a b :b] [a b])
(if-lets [a :a b nil] [a b]))
(defmacro ^:also-cljs when-lets
"Like `when-let` but binds multiple values iff all tests are true."
[bindings & body]
(let [[b1 b2 & bnext] bindings]
(if bnext
`(when-let [~b1 ~b2] (when-lets ~(vec bnext) ~@body))
`(when-let [~b1 ~b2] ~@body))))
(comment (when-lets [a :a b nil] "foo"))
;;;; Types
;; ClojureScript keywords aren't `identical?` and Clojure doesn't have
;; `keyword-identical?`. This util helps alleviate the pain of writing
;; cross-platform code. Ref. http://goo.gl/be8CGP.
#+clj (def kw-identical? identical?)
#+cljs (def kw-identical? keyword-identical?)
(defn atom? [x]
#+clj (instance? clojure.lang.Atom x)
#+cljs (instance? Atom x))
;; (defn- chan? [x]
;; #+clj (instance? clojure.core.async.impl.channels.ManyToManyChannel x)
;; #+cljs (instance? cljs.core.async.impl.channels.ManyToManyChannel x))
#+clj (defn throwable? [x] (instance? Throwable x))
#+clj (defn exception? [x] (instance? Exception x))
(defn error? [x] #+clj (throwable? x)
#+cljs (instance? js/Error x))
(defn error-data [x]
"Returns data map iff `x` is an error of any type on platform."
(when-let [data-map (or (ex-data x) ; ExceptionInfo
#+clj (when (instance? Throwable x) {})
#+cljs (when (instance? js/Error x) {}))]
(merge data-map
#+clj (let [^Throwable t x] ; (catch Throwable t <...>)
{:type* (type t)
:message* (.getMessage t)
:cause* (.getCause t)})
#+cljs (let [err x] ; (catch :default t <...)
{:type* (type err)
:message* (.-message err)
:cause* (.-cause err)}))))
(comment (error-data (Throwable. "foo"))
(error-data (Exception. "foo"))
(error-data (ex-info "foo" {:bar :baz})))
(defn zero-num? [x] (= 0 x)) ; Unlike `zero?`, works on non-nums
(defn pos-num? [x] (and (number? x) (pos? x)))
(defn nneg-num? [x] (and (number? x) (not (neg? x))))
(defn pos-int? [x] (and (integer? x) (pos? x)))
(defn nneg-int? [x] (and (integer? x) (not (neg? x))))
(comment (nneg-int? 0))
(def nnil? (complement nil?))
(def nblank? (complement str/blank?))
(defn nblank-str? [x] (and (string? x) (nblank? x)))
(comment (map nblank-str? ["foo" "" 5]))
(defn nnil=
([x y] (and (nnil? x) (= x y)))
([x y & more] (and (nnil? x) (apply = x y more))))
(comment (nnil= nil nil)
(nnil= :foo :foo :foo))
(defn nvec? "Is `x` a vector of size `n`?" [n x]
(and (vector? x) (= (count x) n)))
(comment (nvec? 2 [:a :b]))
#+clj (def format clojure.core/format) ; For easier encore/format portability
#+cljs
(do
(defn- undefined->nil [x] (if (undefined? x) nil x))
(defn format "Removed from cljs.core 0.0-1885, Ref. http://goo.gl/su7Xkj"
[fmt & args] (apply gstr/format fmt (map undefined->nil args))))
;;;; Validation
;; (defn have*
;; ([cond-or-pred x]
;; (if (ifn? cond-or-pred)
;; (let [pred cond-or-pred] (do (assert (pred x)) x))
;; (let [cond cond-or-pred] (do (assert cond) x))))
;; ([cond-or-pred x & more]
;; (if (ifn? cond-or-pred)
;; (mapv (partial have* cond-or-pred) (into [x] more))
;; (have* cond-or-pred (into [x] more)))))
;; (comment (have* some? 1 2 nil))
;; Helper since we can't use #+clj / #+cljs in macro
(defn throw-assertion-error [msg]
#+clj (throw (AssertionError. msg))
#+cljs (throw (js/Error. msg)))
(defmacro ^:also-cljs have ; asserted
"Experimental general-purpose assertion util.
Use instead of `assert`, use in bindings.
For pre/post conds, use `check` instead."
;; ([x] `(have taoensso.encore/nnil? ~x)) ; Confusing multi-arg behaviour
([cond-or-pred x]
(if-not *assert* x
`(let [cop# ~cond-or-pred]
(if (ifn? cop#)
(let [x# ~x]
(if (cop# x#) x#
(taoensso.encore/throw-assertion-error
(format "Assert failed [pred-form,val]: [%s,%s]"
(pr-str (list '~cond-or-pred '~x))
(pr-str ~x)))))
(if cop# ~x
(taoensso.encore/throw-assertion-error
(format "Assert failed [cond-form,val]: [%s,%s]"
(pr-str '~cond-or-pred)
(pr-str ~cond-or-pred))))))))
;; Allow [] destructuring:
([cond-or-pred x & more]
(let [xs (into [x] more)]
(if-not *assert* xs
`(if (ifn? ~cond-or-pred)
~(mapv (fn [x] `(have ~cond-or-pred ~x)) xs)
(have ~cond-or-pred ~xs))))))
(defmacro ^:also-cljs have-in "Experimental."
;; ([xs] `(have-in taoenso.encore/nnil? ~xs)) ; Maybe...
([cond-or-pred xs]
(if-not *assert* xs
(let [g (gensym "have-in__")]
`(if (ifn? ~cond-or-pred)
(mapv (fn [~g] (have ~cond-or-pred ~g)) ~xs)
(have ~cond-or-pred ~xs))))))
(comment
(have "foo")
(have string? (do (println "eval") "foo"))
(have number? (do (println "eval") "foo"))
(have true (do (println "eval") "foo"))
(have false (do (println "eval") "foo"))
;;
(have string? (do (println "eval1") "foo")
(do (println "eval2") "bar"))
(have number? (do (println "eval1") "foo")
(do (println "eval2") "bar"))
(have true (do (println "eval1") "foo")
(do (println "eval2") "bar"))
(have false (do (println "eval1") "foo")
(do (println "eval2") "bar"))
;;
(let [[x y] (have string? "a" "b")] [x y])
(let [[x y] (have (number? 5) "a" "b")] [x y])
(let [[x y] (have some? "a" nil)] [x y])
;;
(have-in string? ["a" "b"])
(have-in string? (if true ["a" "b"] [1 2]))
(have-in string? (mapv str (range 10)))
(have-in string? [1 2]))
(defmacro ^:also-cljs check-some
"Low-level, general-purpose validator.
Returns first logical false/Ex expression, or nil."
([test & more] `(or ~@(map (fn [test] `(check-some ~test)) (cons test more))))
([test]
(let [[error-id test]
(if (vector? test) ; Id'd test
(do (assert (= (count test) 2)) test)
[nil test])]
(if-cljs
`(let [test# (try ~test (catch :default _# false))]
(when-not test# (or ~error-id '~test :check/falsey)))
`(let [test# (try ~test (catch Exception _# false))]
(when-not test# (or ~error-id '~test :check/falsey)))))))
(defmacro ^:also-cljs check-all
"Low-level, general-purpose validator.
Returns all logical false/Ex expressions, or nil."
([test] `(check-some ~test))
([test & more]
`(let [errors# (->> (list ~@(map (fn [test] `(check-some ~test))
(cons test more)))
(filter identity))]
(when-not (empty? errors#) errors#))))
(defmacro ^:also-cljs check
"General-purpose validator useable in or out of pre/post conds.
Throws a detailed, specific exception on first logical false/Ex form.
Arbitrary data may be attached to exceptions (usu. the data being checked)."
[data & tests]
`(if-let [error# (check-some ~@tests)]
(let [data# ~data]
;; Pre/post failures don't incl. useful info so we throw our own ex (an
;; ex-info for portability):
(throw (ex-info (format "`check` failure: %s\n%s data:\n%s"
(str error#)
(str (or (type data#) "nil"))
(str data#))
{:error error#
:data data#})))
;; For convenient use in pre/post conds:
true))
(comment
(check-some
:data (str/blank? 55) false [:bad-type (string? 55)] nil [:blank (str/blank? 55)])
(check-all
:data (str/blank? 55) false [:bad-type (string? 55)] nil [:blank (str/blank? 55)])
(check
:data (str/blank? 55) false [:bad-type (string? 55)] nil [:blank (str/blank? 55)])
(defn foo [x] {:pre [(check x (or (nil? x) (integer? x)))]
:post [(check x (integer? x))]}
x)
(foo 5)
(foo nil))
(defmacro try-exdata "Useful for `check`-based unit tests, etc."
[& body]
(if-cljs
`(try (do ~@body)
(catch :default e#
(if-let [data# (ex-data e#)]
data# (throw e#))))
`(try (do ~@body)
(catch Exception e#
(if-let [data# (ex-data e#)]
data# (throw e#))))))
(comment (try-exdata (/ 5 0))
(try-exdata (check nil (true? false))))
(defn vec* [x] (if (vector? x) x (vec x)))
(defn set* [x] (if (set? x) x (set x)))
;;; Useful for map assertions, etc. (do *not* check that input is a map)
(defn keys= [m ks] (= (set (keys m)) (set* ks)))
(defn keys<= [m ks] (set/subset? (set (keys m)) (set* ks)))
(defn keys>= [m ks] (set/superset? (set (keys m)) (set* ks)))
(defn keys-nnil? [m ks] (every? #(nnil? (get m %)) ks))
(comment
(keys= {:a :A :b :B :c :C} #{:a :b})
(keys<= {:a :A :b :B :c :C} #{:a :b})
(keys>= {:a :A :b :B :c :C} #{:a :b})
(keys-nnil? {:a :A :b :B :c nil} #{:a :b})
(keys-nnil? {:a :A :b nil :c nil} #{:a :b}))
;;;; Coercions
;; `parse-x` => success, or nil
;; `as-x` => success, (sometimes nil arg), or throw
(defn parse-bool
"Returns x as a unambiguous Boolean, or nil on failure. Requires more
explicit truthiness than (boolean x)."
[x]
(when x
(cond (or (true? x) (false? x)) x
(or (= x "false") (= x "FALSE") (= x "0") (= x 0)) false
(or (= x "true") (= x "TRUE") (= x "1") (= x 1)) true
:else nil)))
(defn as-bool [x] "Like `parse-bool` but throws on unparseable non-nil."
(when x
(let [p (parse-bool x)]
(if-not (nil? p) p
(throw (ex-info (format "as-bool failed: %s" x) {:type (type x)}))))))
(comment (parse-bool "foo")
(as-bool "foo"))
(defn parse-int "Returns x as Long (or JavaScript integer), or nil on failure."
[x]
(when x
#+clj
(cond (number? x) (long x)
(string? x) (try (Long/parseLong x)
(catch NumberFormatException _
(try (long (Float/parseFloat x))
(catch NumberFormatException _ nil))))
:else nil)
#+cljs
(cond (number? x) (long x)
(string? x) (let [x (js/parseInt x 10)]
(when-not (js/isNaN x) x))
:else nil)))
(defn as-int [x] "Like `parse-int` but throws on unparseable non-nil."
(when x
(or (parse-int x)
(throw (ex-info (format "as-int failed: %s" x) {:type (type x)})))))
(comment (parse-int "122.5h")
(as-int "122.5h"))
(defn parse-float "Returns x as Double (or JavaScript float), or nil on failure."
[x]
(when x
#+clj
(cond (number? x) (double x)
(string? x) (try (Double/parseDouble x)
(catch NumberFormatException _ nil))
:else nil)
#+cljs
(cond (number? x) (double x)
(string? x) (let [x (js/parseFloat x)]
(when-not (js/isNan x) x))
:else nil)))
(defn as-float [x] "Like parse-float` but throws on unparseable non-nil."
(or (parse-float x)
(throw (ex-info (format "as-float failed: %s" x) {:type (type x)}))))
(comment (parse-float "122.5h")
(as-float "122.5h"))
;;;; Keywords
(defn stringy? [x] (or (keyword? x) (string? x)))
(defn fq-name "Like `name` but includes namespace in string when present."
[x] (if (string? x) x
(let [n (name x)]
(if-let [ns (namespace x)] (str ns "/" n) n))))
(comment (map fq-name ["foo" :foo :foo.bar/baz]))
(defn explode-keyword [k] (str/split (fq-name k) #"[\./]"))
(comment (explode-keyword :foo.bar/baz))
(defn merge-keywords [ks & [as-ns?]]
(let [parts (->> ks (filterv identity) (mapv explode-keyword) (reduce into []))]
(when-not (empty? parts)
(if as-ns? ; Don't terminate with /
(keyword (str/join "." parts))
(let [ppop (pop parts)]
(keyword (when-not (empty? ppop) (str/join "." ppop))
(peek parts)))))))
(comment (merge-keywords [:foo.bar nil :baz.qux/end nil])
(merge-keywords [:foo.bar nil :baz.qux/end nil] true)
(merge-keywords [:a.b.c "d.e/k"])
(merge-keywords [:a.b.c :d.e/k])
(merge-keywords [nil :k])
(merge-keywords [nil]))
;;;; Bytes
#+clj
(do
(def ^:const bytes-class (Class/forName "[B"))
(defn bytes? [x] (instance? bytes-class x))
(defn ba= [^bytes x ^bytes y] (java.util.Arrays/equals x y))
(defn ba-concat ^bytes [^bytes ba1 ^bytes ba2]
(let [s1 (alength ba1)
s2 (alength ba2)
out (byte-array (+ s1 s2))]
(System/arraycopy ba1 0 out 0 s1)
(System/arraycopy ba2 0 out s1 s2)
out))
(defn ba-split [^bytes ba ^Integer idx]
(let [s (alength ba)]
(when (> s idx)
[(java.util.Arrays/copyOf ba idx)
(java.util.Arrays/copyOfRange ba idx s)])))
(comment (String. (ba-concat (.getBytes "foo") (.getBytes "bar")))
(let [[x y] (ba-split (.getBytes "foobar") 5)]
[(String. x) (String. y)])))
;;;; Math
(defn pow [n exp] (Math/pow n exp))
(defn abs [n] (if (neg? n) (- n) n)) ; #+clj (Math/abs n) reflects
(defn round
[n & [type nplaces]]
(let [modifier (when nplaces (Math/pow 10.0 nplaces))
n* (if-not modifier n (* n modifier))
rounded
(case (or type :round)
;;; Note same API for both #+clj, #+cljs:
:round (Math/round (double n*)) ; Round to nearest int or nplaces
:floor (long (Math/floor (double n*))) ; Round down to -inf
:ceil (long (Math/ceil (double n*))) ; Round up to +inf
:trunc (long n*) ; Round up/down toward zero
(throw (ex-info "Unknown round type" {:type type})))]
(if-not modifier rounded
(/ rounded modifier))))
(def round* round) ; Alias for ns refers
(defn round2 "Optimized common case." [n] (/ (Math/round (* n 100.0)) 100.0))
(comment
(round -1.5 :floor)
(round -1.5 :trunc)
(round 1.1234567 :floor 5)
(round 1.1234567 :round 5))
(defn exp-backoff "Returns binary exponential backoff value."
[nattempt & [{:keys [factor] min' :min max' :max :or {factor 1000}}]]
(let [binary-exp (Math/pow 2 (dec nattempt))
time (* (+ binary-exp (rand binary-exp)) 0.5 factor)]
(long (let [time (if min' (max min' time) time)
time (if max' (min max' time) time)]
time))))
;;;; Date & time
(defn now-dt [] #+clj (java.util.Date.) #+cljs (js/Date.))
(defn now-udt []
#+clj (System/currentTimeMillis)
#+cljs (.getTime (js/Date.)))
(defn now-udt-mock-fn "Useful for testing."
[& [mock-udts]]
(let [mock-udts (or mock-udts (range))
idx (atom -1)]
(fn [] (nth mock-udts (swap! idx inc)))))
(comment (with-redefs [now-udt (now-udt-mock-fn)] (repeatedly 10 now-udt)))
(defn secs->ms [secs] (* secs 1000))
(defn ms->secs [ms] (quot ms 1000))
(defn ms
"Returns number of milliseconds in period defined by given args."
[& {:as opts :keys [years months weeks days hours mins secs msecs ms]}]
{:pre [(every? #{:years :months :weeks :days :hours :mins :secs :msecs :ms}
(keys opts))]}
(round
(+ (if years (* years 1000 60 60 24 365) 0)
(if months (* months 1000 60 60 24 29.53) 0)
(if weeks (* weeks 1000 60 60 24 7) 0)
(if days (* days 1000 60 60 24) 0)
(if hours (* hours 1000 60 60) 0)
(if mins (* mins 1000 60) 0)
(if secs (* secs 1000) 0)
(if msecs msecs 0)
(if ms ms 0))))
(def secs (comp ms->secs ms))
(comment (ms :years 88 :months 3 :days 33)
(secs :years 88 :months 3 :days 33))
(defmacro thread-local-proxy
"Thread-safe proxy wrapper, Ref. http://goo.gl/CEBJnQ (instant.clj)."
[& body] `(proxy [ThreadLocal] [] (initialValue [] (do ~@body))))
(comment
(.get (thread-local-proxy (println "Foo")))
(let [p (thread-local-proxy (println "Foo"))]
(println "---")
(dotimes [_ 100] (.get p))) ; Prints once
(let [p (thread-local-proxy (println "Foo"))]
(println "---")
(.get p)
(.get p)
(future (.get p))
(.get p)) ; Prints twice (2 threads)
)
#+clj
(def ^:private simple-date-format*
"Returns a SimpleDateFormat ThreadLocal proxy."
(memoize
(fn [^String pattern & [{:keys [^Locale locale ^TimeZone timezone]}]]
(thread-local-proxy
(let [^SimpleDateFormat sdformat
(if locale
(SimpleDateFormat. pattern locale)
(SimpleDateFormat. pattern))]
(when timezone (.setTimeZone sdformat timezone))
sdformat)))))
#+clj
(defn simple-date-format
"Returns a thread-local java.text.SimpleDateFormat for simple date formatting
and parsing. Uses JVM's default locale + timezone when unspecified.
(.format (simple-date-format \"yyyy-MMM-dd\") (Date.)) => \"2014-Mar-07\"
Ref. http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Prefer the java.time (Java 8) or Joda-Time (external lib) APIs when available.
Tower also offers facilities built on DateFormat (rather than the more
restrictive SimpleDateFormat)."
;; Note fully qualified type hint!
^java.text.SimpleDateFormat [pattern & [{:keys [locale timezone] :as opts}]]
(.get ^ThreadLocal (simple-date-format* pattern opts)))
(comment (qb 10000 (.format (simple-date-format "yyyy-MMM-dd") (Date.))))
;;;; Collections
(defrecord Swapped [new-val return-val])
(defn swapped [new-val return-val] (Swapped. new-val return-val))
(defn- as-swapped [x] (if (instance? Swapped x) [(:new-val x) (:return-val x)]
[x x]))
(comment ; TODO Debug, Ref. http://dev.clojure.org/jira/browse/CLJ-979
(defrecord Foo1 [x])
(instance? Foo1 (Foo1. "bar"))
(instance? Foo1 (->Foo1 "bar"))
(compile 'taoensso.encore))
;; Recall: no `korks` support since it makes `nil` ambiguous (`[]` vs `[nil]`).
;; This ambiguity extends to (assoc-in {} [] :a), which (along with perf)
;; is why we special case empty/nil ks.
(defn- replace-in*
"Reduces input with
[<type> <ks> <reset-val-or-swap-fn>] or
[<ks> <reset-val-or-swap-fn>] ops."
[?vf-type m ops]
(reduce
(fn [accum ?op]
(if-not ?op ; Allow conditional ops: (when <pred> <op>), etc.
accum
(let [[vf-type ks valf] (if-not ?vf-type ?op (cons ?vf-type ?op))]
(case vf-type
:reset (if (empty? ks) valf (assoc-in accum ks valf))
:swap (if (empty? ks)
(valf accum)
(assoc-in accum ks (valf (get-in accum ks))))))))
m ops))
(defn replace-in "Experimental. For use with `swap!`, etc."
[m & ops] (replace-in* nil m ops))
(comment
(replace-in {}
[:reset [:a] {:b :B :c 100}]
(when false [:reset [:a :b] :B2]) ; conditionals okay
(do (assert true)
[:reset [:a :b] :B3]) ; side-effects okay
(let [my-swap-fn inc] ; `let`s okay
[:swap [:a :c] my-swap-fn]))
(let [a_ (atom {})]
(swap! a_ replace-in
[:reset [:a] {:b :b1 :c :c1 :d 100}]
[:swap [:a :d] inc])))
(defn swap-in!
"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."
([atom_ ks f]
(if (empty? ks)
(loop []
(let [old-val @atom_
[new-val return-val] (as-swapped (f old-val))]
(if-not (compare-and-set! atom_ old-val new-val)
(recur) ; Ref. http://goo.gl/rFG8mW
return-val)))
(loop []
(let [old-val @atom_
old-val-in (get-in old-val ks)
[new-val-in return-val] (as-swapped (f old-val-in))
new-val (assoc-in old-val ks new-val-in)]
(if-not (compare-and-set! atom_ old-val new-val)
(recur)
return-val)))))
;; Experimental:
([atom_ ks f & more] {:pre [(even? (count more))]}
(let [pairs (into [[ks f]] (partition 2 more))]
(swap! atom_ (fn [old-val] (replace-in* :swap old-val pairs))))))
(defn reset-in! "Is to `reset!` as `swap-in!` is to `swap!`."
([atom_ ks new-val]
(if (empty? ks)
(reset! atom_ new-val)
;; Actually need swap! (CAS) to preserve other keys:
(swap! atom_ (fn [old-val] (assoc-in old-val ks new-val)))))
;; Experimental:
([atom_ ks new-val & more] {:pre [(even? (count more))]}
(let [pairs (into [[ks new-val]] (partition 2 more))]
(swap! atom_ (fn [old-val] (replace-in* :reset old-val pairs))))))
(comment
;;; update-in, `swapped`
(let [a_ (atom {:a :A :b :B})] ; Returns new-val (default)
[(swap-in! a_ [] (fn [m] (assoc m :c :C))) @a_])
(let [a_ (atom {:a :A :b :B})] ; Returns old-val
[(swap-in! a_ [] (fn [m] (swapped (assoc m :c :C) m))) @a_])
(let [a_ (atom {:a {:b :B}})] ; Returns new-val-in (default)
[(swap-in! a_ [:a] (fn [m] (assoc m :c :C))) @a_])
(let [a_ (atom {:a {:b :B}})] ; Returns old-val-in
[(swap-in! a_ [:a] (fn [m] (swapped (assoc m :c :C) m))) @a_])
(let [a_ (atom {:a {:b 100}})] (swap-in! a_ [:a :b] inc)) ; => 101
;;; Bulk atomic updates
(let [a_ (atom {})]
(swap-in! a_
[] (constantly {:a {:b :b1 :c :c1 :d 100}})
[:a :b] (constantly :b2)
[:a] #(dissoc % :c)
[:a :d] inc))
(let [a_ (atom {})]
(reset-in! a_
[] {:a {:b :b1 :c :c1 :d 100}}
[:a :b] :b2
[:a :d] inc)))
(defn dissoc-in [m ks & dissoc-ks] (apply update-in m ks dissoc dissoc-ks))
(defn contains-in? [coll ks] (contains? (get-in coll (butlast ks)) (last ks)))
(comment (dissoc-in {:a {:b {:c :C :d :D :e :E}}} [:a :b] :c :e)
(contains-in? {:a {:b {:c :C :d :D :e :E}}} [:a :b :c])
(contains-in? {:a {:b {:c :C :d :D :e :E}}} [:a]))
(defn assoc-some "Assocs each kv iff its value is not nil."
[m & kvs] {:pre [(even? (count kvs))]}
(into (or m {}) (for [[k v] (partition 2 kvs) :when (not (nil? v))] [k v])))
(defn assoc-when "Assocs each kv iff its val is truthy."
[m & kvs] {:pre [(even? (count kvs))]}
(into (or m {}) (for [[k v] (partition 2 kvs) :when v] [k v])))
(comment (assoc-some {:a :A} :b nil :c :C :d nil :e :E))
#+clj (defn queue? [x] (instance? clojure.lang.PersistentQueue x))
#+clj
(defn queue "Returns a PersistentQueue containing the args."
[& items]
(if-not items clojure.lang.PersistentQueue/EMPTY
(into clojure.lang.PersistentQueue/EMPTY items)))
(def seq-kvs
"(seq {:a :A}) => ([:a :A])
(seq-kvs {:a :A}) => (:a :A)"
(partial reduce concat))
(comment (seq-kvs {:a :A :b :B}))
(defn mapply
"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)`."
[f & args]
(apply f (apply concat (butlast args) (last args))))
(defn- clj1098
"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."
[x] (or x {}))
(defn map-kvs [kf vf m]
(if-not m {} ; Note also clj1098-safe
(let [kf (if-not (kw-identical? kf :keywordize) kf (fn [k _] (keyword k)))
vf (if-not (kw-identical? vf :keywordize) vf (fn [_ v] (keyword v)))]
(persistent! (reduce-kv (fn [m k v] (assoc! m (if kf (kf k v) k)
(if vf (vf v v) v)))
(transient {}) m)))))
(defn map-keys [f m] (map-kvs (fn [k _] (f k)) nil m))
(defn map-vals [f m] (map-kvs nil (fn [_ v] (f v)) m))
(defn filter-kvs [predk predv m]
(if-not m {} ; Note also clj1098-safe
(reduce-kv (fn [m k v] (if (and (predk k) (predv v)) m (dissoc m k))) m m)))
(defn filter-keys [pred m] (filter-kvs pred (constantly true) m))
(defn filter-vals [pred m] (filter-kvs (constantly true) pred m))
(comment (filter-vals (complement nil?) {:a :A :b :B :c false :d nil}))
(defn remove-vals
"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."
[pred m]
(if-not m {} ; Note also clj1098-safe
(reduce-kv (fn [m k v] (if (pred v) (dissoc m k) m)) m m)))
(comment (remove-vals nil? {:a :A :b false :c nil :d :D}))
;; (def keywordize-map #(map-kvs :keywordize nil %))
(defn keywordize-map [m]
(if-not m {} ; Note also clj1098-safe
(reduce-kv (fn [m k v] (assoc m (keyword k) v)) {} m)))
(comment (keywordize-map nil)
(keywordize-map {"akey" "aval" "bkey" "bval"}))
(defn as-map "Cross between `hash-map` & `map-kvs`."
[coll & [kf vf]]
{:pre [(or (coll? coll) (nil? coll))
(or (nil? kf) (fn? kf) (kw-identical? kf :keywordize))
(or (nil? vf) (fn? vf))]
:post [(or (nil? %) (map? %))]}
(when coll
(if (empty? coll) {}
(let [kf (if-not (kw-identical? kf :keywordize) kf
(fn [k _] (keyword k)))]
(loop [m (transient {}) [k v :as s] coll]
(let [k (if-not kf k (kf k v))
v (if-not vf v (vf k v))
new-m (assoc! m k v)]
(if-let [n (nnext s)]
(recur new-m n)
(persistent! new-m))))))))
(comment
(as-map nil)
(as-map [])
(as-map ["a" "A" "b" "B" "c" "C"] :keywordize
(fn [k v] (case k (:a :b) (str "boo-" v) v))))
(defn into-all "Like `into` but supports multiple \"from\"s."
([to from] (into to from))
([to from & more] (reduce into (into to from) more)))
(defn interleave-all
"Greedy version of `interleave`.
Ref. https://groups.google.com/d/msg/clojure/o4Hg0s_1Avs/rPn3P4Ig6MsJ"
([] '())
([c1] (lazy-seq c1))
([c1 c2]
(lazy-seq
(let [s1 (seq c1) s2 (seq c2)]
(cond
(and s1 s2)
(cons (first s1) (cons (first s2)
(interleave-all (rest s1) (rest s2))))
s1 s1
s2 s2))))
([c1 c2 & colls]
(lazy-seq
(let [ss (filter identity (map seq (conj colls c2 c1)))]
(concat (map first ss)
(apply interleave-all (map rest ss)))))))
(comment (interleave-all [:a :b :c] [:A :B :C :D :E] [:1 :2]))
(defn distinctv "Prefer `set` when order doesn't matter (much faster)."
([coll] ; `distinctv`
(-> (reduce (fn [[v seen] in]
(if-not (contains? seen in)
[(conj! v in) (conj seen in)]
[v seen]))
[(transient []) #{}]
coll)
(nth 0)
persistent!))
([keyfn coll] ; `distinctv-by`
(-> (reduce (fn [[v seen] in]
(let [in* (keyfn in)]
(if-not (contains? seen in*)
[(conj! v in) (conj seen in*)]
[v seen])))
[(transient []) #{}]
coll)
(nth 0)
persistent!)))
(comment
(distinctv [[:a 1] [:a 1] [:a 2] [:b 1] [:b 3]])
(distinctv second [[:a 1] [:a 1] [:a 2] [:b 1] [:b 3]])
(qb 10000
(distinctv [:a :a :b :c :d :d :e :a :b :c :d])
(doall (distinct [:a :a :b :c :d :d :e :a :b :c :d]))
(set [:a :a :b :c :d :d :e :a :b :c :d])))
(defn distinct-by "Like `sort-by` for distinct. Based on clojure.core/distinct."
[keyfn coll]
(let [step (fn step [xs seen]
(lazy-seq
((fn [[v :as xs] seen]
(when-let [s (seq xs)]
(let [v* (keyfn v)]
(if (contains? seen v*)
(recur (rest s) seen)
(cons v (step (rest s) (conj seen v*)))))))
xs seen)))]
(step coll #{})))
(defn rcompare "Reverse comparator." [x y] (compare y x))
(defn merge-deep-with ; From clojure.contrib.map-utils
"Like `merge-with` but merges maps recursively, applying the given fn
only when there's a non-map at a particular level.
(merge-deep-with + {:a {:b {:c 1 :d {:x 1 :y 2}} :e 3} :f 4}
{:a {:b {:c 2 :d {:z 9} :z 3} :e 100}})
=> {:a {:b {:z 3, :c 3, :d {:z 9, :x 1, :y 2}}, :e 103}, :f 4}"
[f & maps]
(apply
(fn m [& maps]
(if (every? map? maps)
(apply merge-with m maps)
(apply f maps)))
maps))
(def merge-deep (partial merge-deep-with (fn [x y] y)))
(comment (merge-deep {:a {:b {:c {:d :D :e :E}}}}
{:a {:b {:g :G :c {:c {:f :F}}}}}))
(defn greatest "Returns the 'greatest' element in coll in O(n) time."
[coll & [?comparator]]
(let [comparator (or ?comparator rcompare)]
(reduce #(if (pos? (comparator %1 %2)) %2 %1) coll)))
(defn least "Returns the 'least' element in coll in O(n) time."
[coll & [?comparator]]
(let [comparator (or ?comparator rcompare)]
(reduce #(if (neg? (comparator %1 %2)) %2 %1) coll)))
(comment (greatest ["a" "e" "c" "b" "d"]))
(defn repeatedly-into
"Like `repeatedly` but faster and `conj`s items into given collection."
[coll n f]
(if (instance? clojure.lang.IEditableCollection coll)
(loop [v (transient coll) idx 0]
(if (>= idx n) (persistent! v)
(recur (conj! v (f))
(inc idx))))
(loop [v coll idx 0]
(if (>= idx n) v
(recur (conj v (f))
(inc idx))))))
(comment (repeatedly-into [] 10 rand))
(defmacro ^:also-cljs repeatedly-into*
[coll n & body]
`(let [coll# ~coll
n# ~n]
(if #+clj (instance? clojure.lang.IEditableCollection coll#)
#+cljs (implements? IEditableCollection coll#)
(loop [v# (transient coll#) idx# 0]
(if (>= idx# n#)
(persistent! v#)
(recur (conj! v# ~@body)
(inc idx#))))
(loop [v# coll#
idx# 0]
(if (>= idx# n#) v#
(recur (conj v# ~@body)
(inc idx#)))))))
;;;; Strings
(defn substr
"Gives a consistent, flexible, cross-platform substring API with support for:
* Clamping of indexes beyond string limits.
* Negative indexes: [ 0 | 1 | ... | n-1 | n ) or
[ -n | -n+1 | ... | -1 | 0 ).
(start index inclusive, end index exclusive).
Note that `max-len` was chosen over `end-idx` since it's less ambiguous and
easier to reason about - esp. when accepting negative indexes."
[s start-idx & [max-len]]
{:pre [(or (nil? max-len) (nneg-int? max-len))]}
(let [;; s (str s)