Intersection of vector tree

I want to cross a vector tree representing hiccup data structures:

[:div {:class "special"} [:btn-grp '("Hello" "Hi")]] 

Then I want to send a vector by keyword, if a multimethod is defined for this keyword, then it will return another set of vectors that will replace the original tag.

For example, the specified structure will be converted to:

[:div {:class "special"} [:div [:button "Hello"] [:button "Hi"]]]

A custom multimethod will receive a list (hello, hello) as parameters. Then it will return the div containing the buttons.

How to write a function that moves a vector and sends the keyword everything else in the form as a parameter, and then replaces the current form with the returned form?

+3
source share
1 answer
(ns customtags
  (:require [clojure.walk :as walk]))

(def customtags (atom {}))

(defn add-custom-tag [tag f]
  (swap! customtags assoc tag f))

(defn try-transform [[tag & params :as coll]]
  (if-let [f (get @customtags tag)]
    (apply f params)
    coll))

(defmacro defcustomtag [tag params & body]
  `(add-custom-tag ~tag (fn ~params ~@body)))

(defn apply-custom-tags [coll]
  (walk/prewalk
    (fn [x]
      (if (vector? x)
        (try-transform x)
        x)) coll))

Using it:

(require '[customtags :as ct])
(ct/defcustomtag :btn-grp [& coll] (into [:div] (map (fn [x] [:button x]) coll)))
(ct/defcustomtag :button [name] [:input {:type "button" :id name}])

(def data [:div {:class "special"} [:btn-grp "Hello" "Hi"]])

(ct/apply-custom-tags data)
[:div {:class "special"} [:div [:input {:type "button", :id "Hello"}] [:input {:type "button", :id "Hi"}]]]
+1
source

All Articles