-
Notifications
You must be signed in to change notification settings - Fork 21
/
session.cljs
89 lines (75 loc) · 2.45 KB
/
session.cljs
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
(ns reagent.session
(:refer-clojure :exclude [get get-in reset! swap!])
(:require [reagent.core :as reagent :refer [atom]]))
(defonce state (atom {}))
(defn cursor
"Returns a cursor from the state atom."
[ks]
(reagent/cursor state ks))
(defn get
"Get the key's value from the session, returns nil if it doesn't exist."
[k & [default]]
(let [temp-a @(cursor [k])]
(if-not (nil? temp-a) temp-a default)))
(defn put! [k v]
(clojure.core/swap! state assoc k v))
(defn get-in
"Gets the value at the path specified by the vector ks from the session,
returns nil if it doesn't exist."
[ks & [default]]
(let [result @(cursor ks)]
(if-not (nil? result) result default)))
(defn swap!
"Replace the current session's value with the result of executing f with
the current value and args."
[f & args]
(apply clojure.core/swap! state f args))
(defn clear!
"Remove all data from the session and start over cleanly."
[]
(clojure.core/reset! state {}))
(defn reset! [m]
(clojure.core/reset! state m))
(defn remove!
"Remove a key from the session"
[k]
(clojure.core/swap! state dissoc k))
(defn assoc-in!
"Associates a value in the session, where ks is a
sequence of keys and v is the new value and returns
a new nested structure. If any levels do not exist,
hash-maps will be created."
[ks v]
(clojure.core/swap! state assoc-in ks v))
(defn get!
"Destructive get from the session. This returns the current value of the key
and then removes it from the session."[k & [default]]
(let [cur (get k default)]
(remove! k)
cur))
(defn get-in!
"Destructive get from the session. This returns the current value of the path
specified by the vector ks and then removes it from the session."
[ks & [default]]
(let [cur (get-in ks default)]
(assoc-in! ks nil)
cur))
(defn update!
"Updates a value in session where k is a key and f
is the function that takes the old value along with any
supplied args and return the new value. If key is not
present it will be added."
[k f & args]
(clojure.core/swap!
state
#(apply (partial update % k f) args)))
(defn update-in!
"Updates a value in the session, where ks is a
sequence of keys and f is a function that will
take the old value along with any supplied args and return
the new value. If any levels do not exist, hash-maps
will be created."
[ks f & args]
(clojure.core/swap!
state
#(apply (partial update-in % ks f) args)))