Search code examples
clojureclojurescript

how are swap! and the mmap function working here?


This is a snippet from the Reagent project. Looking at complete-all and clear-done, I understand the point is to swap out the modified map. I don't understand how it's being done. The definition of mmap calls for 3 parameters — and complete-all seems to be calling it with two, namely map and #(assoc-in % [1 :done] v). clear-done calls with remove and #(get-in % [1 :done]). I tried using the repl to experiment but couldn't get the requires to work out.

   (ns todomvc.core
      (:require [reagent.core :as r]))

    (defonce todos (r/atom (sorted-map)))

    (defonce counter (r/atom 0))

    (defn add-todo [text]
      (let [id (swap! counter inc)]
        (swap! todos assoc id {:id id :title text :done false})))

    (defn toggle [id] (swap! todos update-in [id :done] not))
    (defn save [id title] (swap! todos assoc-in [id :title] title))
    (defn delete [id] (swap! todos dissoc id))

    (defn mmap [m f a] (->> m (f a) (into (empty m))))
    (defn complete-all [v] (swap! todos mmap map #(assoc-in % [1 :done] v)))
    (defn clear-done [] (swap! todos mmap remove #(get-in % [1 :done])))

Solution

  • The existing map is passed as the first argument to the function. When all else fails...