├── .gitignore ├── LICENSE ├── README.md ├── doc └── intro.md ├── project.clj ├── src └── fresnel │ └── lenses.cljc └── test └── fresnel ├── lenses_test.cljc ├── perf_test.clj └── runner.cljs /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /classes 3 | /checkouts 4 | pom.xml 5 | pom.xml.asc 6 | *.jar 7 | *.class 8 | /.lein-* 9 | /.nrepl-port 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC 2 | LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM 3 | CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. 4 | 5 | 1. DEFINITIONS 6 | 7 | "Contribution" means: 8 | 9 | a) in the case of the initial Contributor, the initial code and 10 | documentation distributed under this Agreement, and 11 | 12 | b) in the case of each subsequent Contributor: 13 | 14 | i) changes to the Program, and 15 | 16 | ii) additions to the Program; 17 | 18 | where such changes and/or additions to the Program originate from and are 19 | distributed by that particular Contributor. A Contribution 'originates' from 20 | a Contributor if it was added to the Program by such Contributor itself or 21 | anyone acting on such Contributor's behalf. Contributions do not include 22 | additions to the Program which: (i) are separate modules of software 23 | distributed in conjunction with the Program under their own license 24 | agreement, and (ii) are not derivative works of the Program. 25 | 26 | "Contributor" means any person or entity that distributes the Program. 27 | 28 | "Licensed Patents" mean patent claims licensable by a Contributor which are 29 | necessarily infringed by the use or sale of its Contribution alone or when 30 | combined with the Program. 31 | 32 | "Program" means the Contributions distributed in accordance with this 33 | Agreement. 34 | 35 | "Recipient" means anyone who receives the Program under this Agreement, 36 | including all Contributors. 37 | 38 | 2. GRANT OF RIGHTS 39 | 40 | a) Subject to the terms of this Agreement, each Contributor hereby grants 41 | Recipient a non-exclusive, worldwide, royalty-free copyright license to 42 | reproduce, prepare derivative works of, publicly display, publicly perform, 43 | distribute and sublicense the Contribution of such Contributor, if any, and 44 | such derivative works, in source code and object code form. 45 | 46 | b) Subject to the terms of this Agreement, each Contributor hereby grants 47 | Recipient a non-exclusive, worldwide, royalty-free patent license under 48 | Licensed Patents to make, use, sell, offer to sell, import and otherwise 49 | transfer the Contribution of such Contributor, if any, in source code and 50 | object code form. This patent license shall apply to the combination of the 51 | Contribution and the Program if, at the time the Contribution is added by the 52 | Contributor, such addition of the Contribution causes such combination to be 53 | covered by the Licensed Patents. The patent license shall not apply to any 54 | other combinations which include the Contribution. No hardware per se is 55 | licensed hereunder. 56 | 57 | c) Recipient understands that although each Contributor grants the licenses 58 | to its Contributions set forth herein, no assurances are provided by any 59 | Contributor that the Program does not infringe the patent or other 60 | intellectual property rights of any other entity. Each Contributor disclaims 61 | any liability to Recipient for claims brought by any other entity based on 62 | infringement of intellectual property rights or otherwise. As a condition to 63 | exercising the rights and licenses granted hereunder, each Recipient hereby 64 | assumes sole responsibility to secure any other intellectual property rights 65 | needed, if any. For example, if a third party patent license is required to 66 | allow Recipient to distribute the Program, it is Recipient's responsibility 67 | to acquire that license before distributing the Program. 68 | 69 | d) Each Contributor represents that to its knowledge it has sufficient 70 | copyright rights in its Contribution, if any, to grant the copyright license 71 | set forth in this Agreement. 72 | 73 | 3. REQUIREMENTS 74 | 75 | A Contributor may choose to distribute the Program in object code form under 76 | its own license agreement, provided that: 77 | 78 | a) it complies with the terms and conditions of this Agreement; and 79 | 80 | b) its license agreement: 81 | 82 | i) effectively disclaims on behalf of all Contributors all warranties and 83 | conditions, express and implied, including warranties or conditions of title 84 | and non-infringement, and implied warranties or conditions of merchantability 85 | and fitness for a particular purpose; 86 | 87 | ii) effectively excludes on behalf of all Contributors all liability for 88 | damages, including direct, indirect, special, incidental and consequential 89 | damages, such as lost profits; 90 | 91 | iii) states that any provisions which differ from this Agreement are offered 92 | by that Contributor alone and not by any other party; and 93 | 94 | iv) states that source code for the Program is available from such 95 | Contributor, and informs licensees how to obtain it in a reasonable manner on 96 | or through a medium customarily used for software exchange. 97 | 98 | When the Program is made available in source code form: 99 | 100 | a) it must be made available under this Agreement; and 101 | 102 | b) a copy of this Agreement must be included with each copy of the Program. 103 | 104 | Contributors may not remove or alter any copyright notices contained within 105 | the Program. 106 | 107 | Each Contributor must identify itself as the originator of its Contribution, 108 | if any, in a manner that reasonably allows subsequent Recipients to identify 109 | the originator of the Contribution. 110 | 111 | 4. COMMERCIAL DISTRIBUTION 112 | 113 | Commercial distributors of software may accept certain responsibilities with 114 | respect to end users, business partners and the like. While this license is 115 | intended to facilitate the commercial use of the Program, the Contributor who 116 | includes the Program in a commercial product offering should do so in a 117 | manner which does not create potential liability for other Contributors. 118 | Therefore, if a Contributor includes the Program in a commercial product 119 | offering, such Contributor ("Commercial Contributor") hereby agrees to defend 120 | and indemnify every other Contributor ("Indemnified Contributor") against any 121 | losses, damages and costs (collectively "Losses") arising from claims, 122 | lawsuits and other legal actions brought by a third party against the 123 | Indemnified Contributor to the extent caused by the acts or omissions of such 124 | Commercial Contributor in connection with its distribution of the Program in 125 | a commercial product offering. The obligations in this section do not apply 126 | to any claims or Losses relating to any actual or alleged intellectual 127 | property infringement. In order to qualify, an Indemnified Contributor must: 128 | a) promptly notify the Commercial Contributor in writing of such claim, and 129 | b) allow the Commercial Contributor tocontrol, and cooperate with the 130 | Commercial Contributor in, the defense and any related settlement 131 | negotiations. The Indemnified Contributor may participate in any such claim 132 | at its own expense. 133 | 134 | For example, a Contributor might include the Program in a commercial product 135 | offering, Product X. That Contributor is then a Commercial Contributor. If 136 | that Commercial Contributor then makes performance claims, or offers 137 | warranties related to Product X, those performance claims and warranties are 138 | such Commercial Contributor's responsibility alone. Under this section, the 139 | Commercial Contributor would have to defend claims against the other 140 | Contributors related to those performance claims and warranties, and if a 141 | court requires any other Contributor to pay any damages as a result, the 142 | Commercial Contributor must pay those damages. 143 | 144 | 5. NO WARRANTY 145 | 146 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON 147 | AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER 148 | EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR 149 | CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A 150 | PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the 151 | appropriateness of using and distributing the Program and assumes all risks 152 | associated with its exercise of rights under this Agreement , including but 153 | not limited to the risks and costs of program errors, compliance with 154 | applicable laws, damage to or loss of data, programs or equipment, and 155 | unavailability or interruption of operations. 156 | 157 | 6. DISCLAIMER OF LIABILITY 158 | 159 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY 160 | CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, 161 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION 162 | LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 163 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 164 | ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE 165 | EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY 166 | OF SUCH DAMAGES. 167 | 168 | 7. GENERAL 169 | 170 | If any provision of this Agreement is invalid or unenforceable under 171 | applicable law, it shall not affect the validity or enforceability of the 172 | remainder of the terms of this Agreement, and without further action by the 173 | parties hereto, such provision shall be reformed to the minimum extent 174 | necessary to make such provision valid and enforceable. 175 | 176 | If Recipient institutes patent litigation against any entity (including a 177 | cross-claim or counterclaim in a lawsuit) alleging that the Program itself 178 | (excluding combinations of the Program with other software or hardware) 179 | infringes such Recipient's patent(s), then such Recipient's rights granted 180 | under Section 2(b) shall terminate as of the date such litigation is filed. 181 | 182 | All Recipient's rights under this Agreement shall terminate if it fails to 183 | comply with any of the material terms or conditions of this Agreement and 184 | does not cure such failure in a reasonable period of time after becoming 185 | aware of such noncompliance. If all Recipient's rights under this Agreement 186 | terminate, Recipient agrees to cease use and distribution of the Program as 187 | soon as reasonably practicable. However, Recipient's obligations under this 188 | Agreement and any licenses granted by Recipient relating to the Program shall 189 | continue and survive. 190 | 191 | Everyone is permitted to copy and distribute copies of this Agreement, but in 192 | order to avoid inconsistency the Agreement is copyrighted and may only be 193 | modified in the following manner. The Agreement Steward reserves the right to 194 | publish new versions (including revisions) of this Agreement from time to 195 | time. No one other than the Agreement Steward has the right to modify this 196 | Agreement. The Eclipse Foundation is the initial Agreement Steward. The 197 | Eclipse Foundation may assign the responsibility to serve as the Agreement 198 | Steward to a suitable separate entity. Each new version of the Agreement will 199 | be given a distinguishing version number. The Program (including 200 | Contributions) may always be distributed subject to the version of the 201 | Agreement under which it was received. In addition, after a new version of 202 | the Agreement is published, Contributor may elect to distribute the Program 203 | (including its Contributions) under the new version. Except as expressly 204 | stated in Sections 2(a) and 2(b) above, Recipient receives no rights or 205 | licenses to the intellectual property of any Contributor under this 206 | Agreement, whether expressly, by implication, estoppel or otherwise. All 207 | rights in the Program not expressly granted under this Agreement are 208 | reserved. 209 | 210 | This Agreement is governed by the laws of the State of Washington and the 211 | intellectual property laws of the United States of America. No party to this 212 | Agreement will bring a legal action under this Agreement more than one year 213 | after the cause of action arose. Each party waives its rights to a jury trial 214 | in any resulting litigation. 215 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Fresnel 2 | 3 | A library for composing lenses and working with complex state objects. This library is a paired down version lens code embedded in Christophe Grand's Enliven. 4 | 5 | 6 | ## Artifact 7 | 8 | All artifacts are published to [clojars](https://clojars.org/fresnel). 9 | 10 | [![Clojars Project](http://clojars.org/fresnel/latest-version.svg)](http://clojars.org/fresnel) 11 | 12 | ### Note: Breaking changes in 0.3.0-SNAPSHOT 13 | 14 | If you reified the Lens protocol directly you will have to now reify IFetch and IPutback protocols. 15 | 16 | ## Concepts 17 | 18 | The concept of a lens is very simple. A lens consists of two methods; one that transforms the state object into desired form and one that takes a transform object and pushes its state back into the main state object. Fresnel provides a mechanism to define lenses and to compose them. Fresnel builds on the concepts that already existing in Clojure. In Clojure we see two types of lenses for associative structures. The first is the keyword and we use get and assoc as the transform functions. The other is composition of these lenses in the form of a vector. We use get-in and assoc-in as transform functions in this case. Fresnel extends this concept beyond associative structures and unifies the access methods under a single protocol Lens. 19 | 20 | ```clj 21 | (def state {:a {:aa "a1,b1,c1" 22 | :ab 2} 23 | :b {:ba "a2,b2,c2" 24 | :bb 2}}) 25 | 26 | ;fresnel supports custom lenses 27 | (deflens comma-to-map [oval nval] 28 | :fetch 29 | (reduce #(assoc %1 (.trim %2) true) {} (split oval #",")) 30 | :putback 31 | (reduce #(if %1 (str %2 "," %1) %2) 32 | nil 33 | (filter #(nval %1) (keys nval)))) 34 | 35 | ;fresnel supports composing of lenses 36 | (def compound-lens [:a :aa comma-to-map]) 37 | 38 | (fetch state compound-lens) 39 | ;{:a1 true :b1 true :c1 true} 40 | 41 | (def new-state 42 | (putback state 43 | compound-lens 44 | {:a1 false :b1 true :c1 true :d1 true})) 45 | 46 | ;;new-state {:a {:aa "b1,c1,d1" :ab 2} 47 | ;; :b {:ba "a2,b2,c2" :bb 2}}) 48 | 49 | 50 | ``` 51 | 52 | 53 | ## License 54 | 55 | Copyright © 2014 Creighton Kirkendall 56 | 57 | Distributed under the Eclipse Public License either version 1.0 or (at 58 | your option) any later version. 59 | -------------------------------------------------------------------------------- /doc/intro.md: -------------------------------------------------------------------------------- 1 | # Introduction to segments 2 | 3 | TODO: write [great documentation](http://jacobian.org/writing/great-documentation/what-to-write/) 4 | -------------------------------------------------------------------------------- /project.clj: -------------------------------------------------------------------------------- 1 | (defproject fresnel "0.3.2-SNAPSHOT" 2 | :description "A library for composing lenses and working with complex state objects" 3 | :url "https://github.com/ckirkendall/fresnel" 4 | :license {:name "Eclipse Public License" 5 | :url "http://www.eclipse.org/legal/epl-v10.html"} 6 | :dependencies [[org.clojure/clojure "1.9.0"] 7 | [org.clojure/clojurescript "1.10.520"]] 8 | :plugins [[lein-shell "0.5.0"]] 9 | :source-paths ["src"] 10 | :test-paths ["src" "test"] 11 | :doo {:build "test" 12 | :alias {:default [:node]}} 13 | :release-tasks [["vcs" "assert-committed"] 14 | ["change" "version" "leiningen.release/bump-version" "release"] 15 | ["shell" "echo" "bumped version"] 16 | ["vcs" "commit"] 17 | ["vcs" "tag" "v" "--no-sign"] ; disable signing and add "v" prefix 18 | ["shell" "echo" "tagged version"] 19 | ["deploy" "clojars"] 20 | ["shell" "echo" "deployed"] 21 | ["change" "version" "leiningen.release/bump-version"] 22 | ["vcs" "commit"] 23 | ["shell" "echo" "bump version back to snapshot"] 24 | ["vcs" "push"] 25 | ["shell" "echo" "pushed"]] 26 | :profiles {:dev {:dependencies [[lein-doo "0.1.10"]] 27 | :plugins [[lein-cljsbuild "1.1.7"] 28 | [lein-doo "0.1.10"]] 29 | :cljsbuild {:builds [{:id "dev" 30 | :source-paths ["src" "test"] 31 | :compiler {:main fresnel.runner 32 | :output-to "target/main.js" 33 | :optimizations :whitespace 34 | :pretty-print true}} 35 | {:id "test" 36 | :source-paths ["src" "test"] 37 | :compiler {:main fresnel.runner 38 | :output-to "target/doo/test.js" 39 | :output-dir "target/doo/out" 40 | :target :nodejs 41 | :language-in :ecmascript5 42 | :optimizations :none}}]}}}) 43 | -------------------------------------------------------------------------------- /src/fresnel/lenses.cljc: -------------------------------------------------------------------------------- 1 | (ns fresnel.lenses 2 | (:refer-clojure :exclude [key])) 3 | 4 | (declare fetch-in putback-in) 5 | 6 | (defprotocol IFetch 7 | (-fetch [seg value])) 8 | 9 | (defprotocol IPutback 10 | (-putback [seg value subvalue])) 11 | 12 | 13 | (defn fetch-lens [x] 14 | (if (satisfies? IFetch x) x 15 | (throw (#?(:clj IllegalArgumentException. :cljs js/Error) 16 | (str "Lens does not satisfy IFetch protocol: " (pr-str x)))))) 17 | 18 | (defn putback-lens [x] 19 | (if (satisfies? IPutback x) x 20 | (throw (#?(:clj IllegalArgumentException. :cljs js/Error) 21 | (str "Lens does not satisfy IPutback protocol: " (pr-str x)))))) 22 | 23 | (defn bi-lens [x] 24 | (if (and (fetch-lens x) 25 | (putback-lens x)) 26 | x)) 27 | 28 | (defn fetch [value seg] 29 | (try (-fetch seg value) 30 | (catch #?(:clj IllegalArgumentException :cljs js/Error) e 31 | (fetch-lens seg) 32 | (throw e)))) 33 | 34 | (defn putback [value seg subvalue] 35 | (-putback (putback-lens seg) value subvalue)) 36 | 37 | 38 | ;; This is used to dissoc a key in an associtive structure. 39 | ;; if used as the value of putback it will trigger a 40 | ;; dissoc on the seg. 41 | (def dissoc-trigger :fresnel/dissoc) 42 | 43 | 44 | (defn safe-assoc [value seg sub-val] 45 | (if (identical? sub-val dissoc-trigger) 46 | (dissoc value seg) 47 | (assoc value seg sub-val))) 48 | 49 | 50 | (defprotocol ISafeNth 51 | (-safe-nth [value n])) 52 | 53 | (defprotocol ISafeNumAssoc 54 | (-safe-num-assoc [value seg sub-val])) 55 | 56 | 57 | (extend-type #?(:clj clojure.lang.Keyword 58 | :cljs cljs.core.Keyword) 59 | IFetch 60 | (-fetch [seg value] (get value seg)) 61 | IPutback 62 | (-putback [seg value subval] 63 | (let [val (if (nil? value) {} value)] 64 | (safe-assoc val seg subval)))) 65 | 66 | (extend-type #?(:clj clojure.lang.Symbol 67 | :cljs cljs.core.Symbol) 68 | IFetch 69 | (-fetch [seg value] (get value seg)) 70 | IPutback 71 | (-putback [seg value subval] 72 | (let [val (if (nil? value) {} value)] 73 | (safe-assoc val seg subval)))) 74 | 75 | (extend-type #?(:clj String 76 | :cljs string) 77 | IFetch 78 | (-fetch [seg value] (get value seg)) 79 | IPutback 80 | (-putback [seg value subval] 81 | (let [val (if (nil? value) {} value)] 82 | (safe-assoc val seg subval)))) 83 | 84 | (extend-type #?(:clj Number 85 | :cljs number) 86 | IFetch 87 | (-fetch [seg value] (when (not (nil? value)) 88 | (-safe-nth value seg))) 89 | IPutback 90 | (-putback [seg value subval] 91 | (let [val (if (nil? value) [] value)] 92 | (-safe-num-assoc value seg subval)))) 93 | 94 | (extend-type #?(:clj clojure.lang.PersistentVector 95 | :cljs cljs.core/PersistentVector) 96 | IFetch 97 | (-fetch [seg value] (fetch-in value seg)) 98 | IPutback 99 | (-putback [seg value subval] (putback-in value seg subval)) 100 | ISafeNth 101 | (-safe-nth [value seg] (nth value seg)) 102 | ISafeNumAssoc 103 | (-safe-num-assoc [value seg sub-value] (assoc value seg sub-value))) 104 | 105 | (extend-type #?(:clj clojure.lang.PersistentList 106 | :cljs cljs.core/List) 107 | IFetch 108 | (-fetch [seg value] (fetch-in value seg)) 109 | IPutback 110 | (-putback [seg value subval] (putback-in value seg subval))) 111 | 112 | (extend-type #?(:clj clojure.lang.PersistentArrayMap 113 | :cljs cljs.core/PersistentArrayMap) 114 | ISafeNth 115 | (-safe-nth [value seg] (get value seg)) 116 | ISafeNumAssoc 117 | (-safe-num-assoc [value seg sub-value] (safe-assoc value seg sub-value))) 118 | 119 | (extend-type #?(:clj clojure.lang.PersistentHashMap 120 | :cljs cljs.core/PersistentHashMap) 121 | ISafeNth 122 | (-safe-nth [value seg] (get value seg)) 123 | ISafeNumAssoc 124 | (-safe-num-assoc [value seg sub-value] (safe-assoc value seg sub-value))) 125 | 126 | 127 | (extend-type #?(:clj Object 128 | :cljs object) 129 | ISafeNth 130 | (-safe-nth [value seg] 131 | (if (vector? value) 132 | (get value seg) 133 | (loop [idx 0 val value] 134 | (if (or (empty? val) (>= idx seg)) 135 | (first val) 136 | (recur (inc idx) (rest val)))))) 137 | ISafeNumAssoc 138 | (-safe-num-assoc [value seg sub-val] 139 | (cond 140 | (vector? value) 141 | (assoc value seg sub-val) 142 | 143 | (map? value) 144 | (safe-assoc value seg sub-val) 145 | 146 | :else ;seq 147 | (loop [idx 0 val value accum []] 148 | (cond 149 | (>= idx seg) (concat (conj accum sub-val) (rest val)) 150 | (empty? val) (recur (inc idx) val (conj accum nil)) 151 | :else (recur (inc idx) (rest val) (conj accum (first val)))))))) 152 | 153 | (defn key [ky] 154 | (reify 155 | IFetch 156 | (-fetch [seg value] (get value ky)) 157 | IPutback 158 | (-putback [seg value subval] 159 | (let [val (if (nil? value) {} value)] 160 | (assoc val ky subval))))) 161 | 162 | (defn- bound [mn n mx] 163 | (-> n (max mn) (min mx))) 164 | 165 | (defn spliceable? [x] 166 | (or (nil? x) (sequential? x))) 167 | 168 | (defrecord Slice [from to] 169 | IFetch 170 | (-fetch [seg x] 171 | (let [n (count x)] 172 | (subvec x (bound 0 from n) (bound 0 to n)))) 173 | IPutback 174 | (-putback [seg x v] 175 | (let [n (count x)] 176 | (-> x 177 | (subvec 0 (bound 0 from n)) 178 | (into (if (spliceable? v) v (list v))) 179 | (into (subvec x (bound 0 to n) n)))))) 180 | 181 | (defn slice [from to] (Slice. from to)) 182 | 183 | (defn slice? [seg] (instance? Slice seg)) 184 | 185 | 186 | (defn create-fetch-lens [fetch-fn] 187 | (reify 188 | IFetch 189 | (-fetch [seg value] (fetch-fn seg value)))) 190 | 191 | 192 | (defn create-putback-lens [putback-fn] 193 | (reify 194 | IPutback 195 | (-putback [seg value subvalue] (putback-fn seg value subvalue)))) 196 | 197 | 198 | (defn create-bi-lens [fetch-fn putback-fn] 199 | (reify 200 | IFetch 201 | (-fetch [seg value] (fetch-fn seg value)) 202 | IPutback 203 | (-putback [seg value subvalue] (putback-fn seg value subvalue)))) 204 | 205 | 206 | (defn create-lens [fetch-fn putback-fn] 207 | {:pre [(or fetch putback)]} 208 | (cond 209 | (and fetch-fn putback-fn) 210 | (create-bi-lens fetch-fn putback-fn) 211 | 212 | fetch-fn 213 | (create-fetch-lens fetch-fn) 214 | 215 | putback-fn 216 | (create-putback-lens putback-fn))) 217 | 218 | 219 | (defmacro deffetch [name doc? initial-args & methods] 220 | (let [[name initial-args methods] (if (string? doc?) 221 | [(vary-meta name assoc :doc doc?) initial-args methods] 222 | [name doc? (cons initial-args methods)]) 223 | [value-arg & args] initial-args] 224 | `(deflens ~name [~value-arg nil ~@args] :fetch ((fn [] ~@methods))))) 225 | 226 | 227 | (defmacro defputback [name doc? initial-args & methods] 228 | (let [[name initial-args methods] (if (string? doc?) 229 | [(vary-meta name assoc :doc doc?) initial-args methods] 230 | [name doc? (cons initial-args methods)])] 231 | `(deflens ~name ~initial-args :putback ((fn [] ~@methods))))) 232 | 233 | 234 | (defmacro deflens [name doc? initial-args & methods] 235 | (let [[name initial-args methods] (if (string? doc?) 236 | [(vary-meta name assoc :doc doc?) initial-args methods] 237 | [name doc? (cons initial-args methods)]) 238 | [value-arg subvalue-arg & args] initial-args 239 | auto-segment (empty? args) 240 | [args [_ & rest-arg]] (split-with #(not= (clojure.core/name %) "&") args) 241 | plain-args (take (count args) (repeatedly gensym)) 242 | plain-rest-arg (when rest-arg (gensym)) 243 | methods (reduce (fn [m [k v]] 244 | (assoc m k (case k 245 | :fetch `(fn [_# ~value-arg] ~v) 246 | :putback `(fn [_# ~value-arg ~subvalue-arg] ~v)))) 247 | {} 248 | (partition 2 methods)) 249 | 250 | f `(fn [~@plain-args ~@(when plain-rest-arg `[& ~plain-rest-arg])] 251 | (let [~@(interleave args plain-args) 252 | ~@(when plain-rest-arg [rest-arg plain-rest-arg])] 253 | (fresnel.lenses/create-lens ~(:fetch methods) ~(:putback methods) )))] 254 | `(def ~name ~(if auto-segment (list f) f)))) 255 | 256 | 257 | 258 | (defn fetch-in [obj path] 259 | (reduce fetch obj path)) 260 | 261 | 262 | (defn putback-in [obj [seg & path] value] 263 | (when seg 264 | (if (empty? path) 265 | (putback obj seg value) 266 | (putback obj seg (putback-in (fetch obj seg) path value))))) 267 | -------------------------------------------------------------------------------- /test/fresnel/lenses_test.cljc: -------------------------------------------------------------------------------- 1 | (ns fresnel.lenses-test 2 | (:require-macros [fresnel.lenses :refer [deflens deffetch defputback]]) 3 | (:require #?(:clj [clojure.test :refer [deftest testing is are]] 4 | :cljs [clojure.test :refer-macros [deftest testing is are]]) 5 | [fresnel.lenses :refer [#?(:clj deflens) #?(:clj deffetch) #?(:clj defputback) 6 | IFetch IPutback fetch putback create-lens slice 7 | key dissoc-trigger]] 8 | [clojure.string :refer [split]])) 9 | 10 | (deflens comma-to-map [oval nval] 11 | :fetch 12 | (reduce #(assoc %1 (.trim %2) true) {} (split oval #",")) 13 | :putback 14 | (reduce #(if %1 (str %2 "," %1) %2) 15 | nil 16 | (filter #(nval %1) (keys nval)))) 17 | 18 | (deftest fetch-tests 19 | (testing "fetching using simple keyword" 20 | (let [data {:a "success"}] 21 | (is (= "success" (fetch data :a))))) 22 | (testing "fetching using a string" 23 | (let [data {"a" "success"}] 24 | (is (= "success" (fetch data "a"))))) 25 | (testing "fetching using a string" 26 | (let [data {'a "success"}] 27 | (is (= "success" (fetch data 'a))))) 28 | (testing "fetching using a number on a vector" 29 | (let [data ["a" "b" "c"]] 30 | (is (= "b" (fetch data 1))))) 31 | (testing "fetching using a number on a list" 32 | (let [data '("a" "b" "c")] 33 | (is (= "b" (fetch data 1))))) 34 | (testing "fetching using a simple custom segment" 35 | (let [seg (create-lens (fn [_ data] (nth data 1)) 36 | (fn [_ _ nval] nval)) 37 | data ["a" "b" "c"]] 38 | (is (= "b" (fetch data seg))))) 39 | (testing "fetching using a complex segement" 40 | (let [data "a,b,c"] 41 | (is (= {"a" true 42 | "b" true 43 | "c" true} 44 | (fetch data comma-to-map))))) 45 | (testing "fetching using slice segment" 46 | (let [data [:a :b :c :d :e :f]] 47 | (is (= '(:c :d) 48 | (fetch data (slice 2 4))))))) 49 | 50 | 51 | (deftest putback-tests 52 | (testing "putback using simple keyword" 53 | (let [data {:a "fail"}] 54 | (is (= {:a "success"} (putback data :a "success"))))) 55 | (testing "putback using a string" 56 | (let [data {"a" "fail"}] 57 | (is (= {"a" "success"} (putback data "a" "success"))))) 58 | (testing "putback using a string" 59 | (let [data {'a "fail"}] 60 | (is (= {'a "success"} (putback data 'a "success"))))) 61 | (testing "putback using a number on a vector" 62 | (let [data ["a" "fail" "c"]] 63 | (is (= ["a" "b" "c"] (putback data 1 "b"))))) 64 | (testing "putback using a number on a list" 65 | (let [data '("a" "fail" "c")] 66 | (is (= '("a" "b" "c") (putback data 1 "b"))))) 67 | (testing "putback using a custom segment" 68 | (let [seg (create-lens (fn [_ data] (nth data 1)) 69 | (fn [_ data nval] (assoc data 1 nval))) 70 | data ["a" "fail" "c"]] 71 | (is (= ["a" "b" "c"] (putback data seg "b"))))) 72 | (testing "putback using a complex segement" 73 | (let [data "a,b,c" 74 | res (putback data 75 | comma-to-map 76 | (assoc (fetch data comma-to-map) "d" true))] 77 | (is (or (= "a,b,c,d" res) 78 | (= "d,c,b,a" res))))) 79 | (testing "fetching using slice segment" 80 | (let [data [:a :b :c :d :e :f]] 81 | (is (= '(:a :b :t :t :t :e :f) 82 | (putback data (slice 2 4) [:t :t :t])))))) 83 | 84 | 85 | (deftest fetch-in-tests 86 | (testing "basic compond map with keys" 87 | (let [data {:a {:b {"c" 1 :d 2} 'e 3} :f [1 2 3 4]}] 88 | (are [x y] (= x (fetch data y)) 89 | 1 [:a :b "c"] 90 | 3 [:a 'e] 91 | 4 [:f 3] 92 | {"c" 1 :d 2} [:a :b]))) 93 | (testing "compond map with complex segment" 94 | (let [data {:a ["x,y,z" "a,b,c"]}] 95 | (is (= true (fetch data [:a 1 comma-to-map "b"]))) 96 | (is (= nil (fetch data [:a 1 comma-to-map "d"])))))) 97 | 98 | 99 | (deftest putback-in-tests 100 | (testing "basic compond map with keys" 101 | (let [data {:a {:b {"c" 1 :d 2} 'e 3} :f [1 2 3 4]}] 102 | (is (= {:a {:b {"c" 1 :d 2} 'e 3} :f [1 2 5 4]} 103 | (putback data [:f 2] 5))) 104 | (is (= {:a {:b {"c" 1 :d 5} 'e 3} :f [1 2 3 4]} 105 | (putback data [:a :b :d] 5))))) 106 | (testing "compond map with complex segment" 107 | (let [data {:a ["x,y,z" "a,b,c"]} 108 | res (putback data [:a 1 comma-to-map "b"] false)] 109 | (is (or (= {:a ["x,y,z" "a,c"]} res) 110 | (= {:a ["x,y,z" "c,a"]} res)))))) 111 | 112 | 113 | (deffetch fetch-tmp [val] 114 | val) 115 | 116 | (deftest deffetch-tests 117 | (testing "a deffetch reifies IFetch" 118 | (is (satisfies? IFetch fetch-tmp)) 119 | (is (= (fetch 3 fetch-tmp) 3)))) 120 | 121 | 122 | (defputback putback-tmp [oval nval] 123 | (conj oval nval)) 124 | 125 | (deftest defputback-tests 126 | (testing "a defputback reifies IFetch" 127 | (is (satisfies? IPutback putback-tmp)) 128 | (is (= (putback [] putback-tmp 3) [3])))) 129 | 130 | 131 | (deftest assoc-in-compatibility-test 132 | (let [state {:a {:b :c}}] 133 | (testing "basic compatibility with assoc-in and get-in" 134 | ;; assoc-in 135 | (is (= {:foo {:bar {:baz 100}}} 136 | (putback {:foo {:bar {:baz 0}}} [:foo :bar :baz] 100))) 137 | (is (= {:foo 1 :bar 2 :baz 100} 138 | (putback {:foo 1 :bar 2 :baz 3} [:baz] 100))) 139 | (is (= [{:foo [{:bar 2} {:baz 3}]} {:foo [{:bar 2} {:baz 100}]}] 140 | (putback [{:foo [{:bar 2} {:baz 3}]}, {:foo [{:bar 2} {:baz 3}]}] 141 | [1 :foo 1 :baz] 100))) 142 | (is (= [{:foo 1, :bar 2} {:foo 1, :bar 100}] 143 | (putback [{:foo 1 :bar 2}, {:foo 1 :bar 2}] [1 :bar] 100))) 144 | #?(:clj (is (thrown? IndexOutOfBoundsException (putback [] [1 :bar] 100))) 145 | :cljs (is (thrown? js/Error (putback [] [1 :bar] 100)))) 146 | (is (= {:bar {:foo 100}} 147 | (putback nil [:bar :foo] 100))) 148 | 149 | ;; get-in 150 | (is (= 1 (fetch {:foo 1 :bar 2} [:foo]))) 151 | (is (= 2 (fetch {:foo {:bar 2}} [:foo :bar]))) 152 | (is (= 1 (fetch [{:foo 1}, {:foo 2}] [0 :foo]))) 153 | (is (= 4 (fetch [{:foo 1 :bar [{:baz 1}, {:buzz 2}]}, {:foo 3 :bar [{:baz 3}, {:buzz 4}]}] 154 | [1 :bar 1 :buzz])))))) 155 | 156 | 157 | (deftest complex-keys-test 158 | (testing "making sure the complex key can be created with key function" 159 | (is (= {:a :b} 160 | (fetch {[0 1] {:a :b}} [(key [0 1])]))) 161 | (is (= {[0 1] {:a :c}} 162 | (putback {[0 1] {:a :b}} [(key [0 1]) :a] :c))) 163 | (is (= {[0 1] {:a :c}} 164 | (putback {} [(key [0 1]) :a] :c))))) 165 | 166 | (deftest dissoc-test 167 | (testing "making sure that putback with the dissoc-trigger causes a dissoc of the key" 168 | (is (= {:a :b} 169 | (putback {:a :b :c :d} :c dissoc-trigger))))) 170 | -------------------------------------------------------------------------------- /test/fresnel/perf_test.clj: -------------------------------------------------------------------------------- 1 | (ns fresnel.perf-test 2 | (:require [fresnel.core :refer :all])) 3 | 4 | (def state {:a [{:b [:c]}]}) 5 | 6 | (defn run-f-test [state path cnt] 7 | (time 8 | (dotimes [_ cnt] 9 | (fetch state path)))) 10 | 11 | (defn run-test [state path cnt] 12 | (time 13 | (dotimes [_ cnt] 14 | (get-in state path)))) 15 | 16 | 17 | -------------------------------------------------------------------------------- /test/fresnel/runner.cljs: -------------------------------------------------------------------------------- 1 | (ns fresnel.runner 2 | (:require [cljs.test :as t :include-macros true :refer [report]] 3 | [doo.runner :include-macros true :refer [doo-all-tests]] 4 | [fresnel.lenses-test])) 5 | 6 | (doo-all-tests #"fresnel.*test") 7 | --------------------------------------------------------------------------------