-
Notifications
You must be signed in to change notification settings - Fork 21
/
cursor.cljs
58 lines (46 loc) · 1.48 KB
/
cursor.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
(ns citrus.cursor
(:require [goog.object :as gobj]))
(deftype ReduceCursor [ref path reducer meta]
Object
(equiv [this other]
(-equiv this other))
IAtom
IMeta
(-meta [_] meta)
IEquiv
(-equiv [this other]
(identical? this other))
IDeref
(-deref [_]
(-> (-deref ref)
(get-in path)
(reducer)))
IWatchable
(-add-watch [this key callback]
(add-watch ref (list this key)
(fn [_ _ oldv newv]
(let [old (reducer (get-in oldv path))
new (reducer (get-in newv path))]
(when (not= old new)
(callback key this old new)))))
this)
(-remove-watch [this key]
(remove-watch ref (list this key))
this)
IHash
(-hash [this] (goog/getUid this))
IPrintWithWriter
(-pr-writer [this writer opts]
(-write writer "#object [citrus.cursor.ReduceCursor ")
(pr-writer {:val (-deref this)} writer opts)
(-write writer "]")))
(defn reduce-cursor-in
"Given atom with deep nested value, path inside it and reducing function, creates an atom-like structure
that can be used separately from main atom, but only for reading value:
(def state (atom {:users {\"Ivan\" {:children [1 2 3]}}}))
(def ivan (citrus.cursor/reduce-cursor-in state [:users \"Ivan\" :children] last))
(deref ivan) ;; => 3
Returned value supports deref, watches and metadata.
The only supported option is `:meta`"
[ref path reducer & {:as options}]
(ReduceCursor. ref path reducer (:meta options)))