-
Notifications
You must be signed in to change notification settings - Fork 0
/
shmap.clj
75 lines (65 loc) · 1.75 KB
/
shmap.clj
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
(ns shmap
(:require [clojure.test :refer [deftest is]]))
(defmacro shmap
"Property value shorthand, like in js. When you are too lazy to specify both key and value.
```
(let [one 1
two 2
:three three
ten 10]
(shmap one
two
:three three
ten)) => {:one 1, :two 2, :three 3, :ten 10}
```
"
[& symbols]
(loop [symbols symbols
res {}]
(let [[left right] (take 2 symbols)
both-symbols? (every? symbol? [left right])]
(if (seq symbols)
(recur (rest (if (or both-symbols?
(not (symbol? left)))
(rest symbols)
symbols))
(merge res
(cond
both-symbols?
{(keyword left) left
(keyword right) right}
(not (symbol? left))
{left right}
:else
{(keyword left) left}
)))
res))))
(defmacro shmap-test [expected & symbols]
`(is (= ~expected
(shmap ~@symbols))))
(deftest basic
(let [one 1
two 2
ten 10
three 3
expected {:two two :one one, :ten ten, :three three}]
(shmap-test expected
:three three
one
two
ten)
(shmap-test expected
one
:three three
two
ten )
(shmap-test expected
one
two
:three three
ten )
(shmap-test expected
one
two
ten
:three three)))