-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.cljc
111 lines (94 loc) · 2.6 KB
/
util.cljc
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
(ns grafeo.util
(:require [#?(:clj cheshire.core :cljs goog.json) :as json]
[clojure.pprint :as pprint]
[clojure.spec.alpha :as s]
[clojure.string :as str]
[clojure.walk :as walk]))
(defn encode-json
"Encode `obj` as JSON."
[obj]
#?(:clj (json/encode obj)
:cljs (json/serialize (clj->js obj))))
(defn decode-json
"Decode `s` as JSON."
[s]
#?(:clj (json/decode s keyword)
:cljs (js->clj (js/JSON.parse s) :keywordize-keys true)))
(defn simple-class-name
"Given an symbol of a class, returns it's simple name. Leaves the
fragment spread '... as is."
[sym]
(str/replace (str sym) #"([^.].*\.)" ""))
(defn conform!
"Conform `x` against `spec`, or raise an exception."
[spec x]
(let [ast (s/conform spec x)]
(if (s/invalid? ast)
(throw (ex-info (str "Can't conform " x " against " spec ".")
(s/explain-data spec x)))
ast)))
(defn transform-keys [m transform-fn]
(let [f (fn [[k v]]
[(transform-fn k) v])]
(walk/postwalk
(fn [x]
(if (map? x)
(into {} (map f x))
x))
m)))
(defn strip-keys [m ks]
(let [ks (set ks)
f (fn [[k v]]
(when-not (contains? ks k)
[k v]))]
(walk/postwalk
(fn [x]
(if (map? x)
(into {} (map f x))
x))
m)))
(defn reset-metadata [m]
(let [f (fn [[k v]]
(if (= k :alumbra/metadata)
[k (-> (merge v {:column 0 :row 0})
(dissoc :index))]
[k v]))]
(walk/postwalk
(fn [x]
(if (map? x)
(into {} (map f x))
x))
m)))
(defn transform-loc [m]
(let [f (fn [[k v]]
(if (= k :loc)
[k {:startToken
{:column (.. v -startToken -column)
:start (.. v -startToken -start)
:line (.. v -startToken -line)}}]
[k v]))]
(walk/postwalk
(fn [x]
(if (map? x)
(into {} (map f x))
x))
m)))
(defn strip-metadata [m]
(strip-keys m #{:alumbra/metadata}))
(defn strip-non-null [s]
(str/replace (name s) #"!$" ""))
(defn strip-loc [m]
(strip-keys m #{:loc}))
(defn strip-variable [s]
(some-> s name (.substring 1)))
(defn pprint [x]
(binding [*print-namespace-maps* false]
(pprint/pprint x)))
(defn hyphenate [s]
(some-> s name (str/replace "_" "-")))
(defn hyphenate-keys [m]
(transform-keys m (comp keyword hyphenate)))
(defn underscore [s]
(some-> s name (str/replace "-" "_")))
(defn underscore-keys [m]
(transform-keys m (comp keyword underscore)))