001  (ns vl-data-insert.utils
002    ^{:author "wactbprot"
003      :doc "Utils for data insert tasks."}
004    (:require [clojure.string :as string]))
005  
006  
007  (defn ensure-vec
008    "Ensures that `v` is a vector.
009  
010    Example:
011    ```clojure
012    (ensure-vec nil) ;!
013    ;; nil
014    (ensure-vec 1)
015    ;; [1]
016    (ensure-vec [1])
017    ;; [1]
018    ```"
019    [v]
020    (when v (if (vector? v) v [v])))
021  
022  (defn vector-if
023    "Makes the value `v` behind the keyword `kw` a vector if `v` is not
024    nil."
025    [m kw]
026    (if (and (map? m) (keyword? kw))
027      (if-let [v (kw m)] (assoc m kw (ensure-vec v)) m)))
028  
029  (defn replace-if
030    "Replaces `v`alue of `k`ey in struct if `v`is not `nil`.
031  
032    Example:
033    ```clojure
034    (replace-if {:Type \"a\"} :Type \"b\")
035    ;; {:Type \"b\"}
036    ```
037    "
038    [m k v]
039    (if (and (some? v) (keyword? k)) (assoc m k v) m))
040  
041  (defn append-if
042    "Appends `v` to the value of `k`. If `k` does not exist in `m`,
043    `k [v]` is assoced.  If `k` does exist in `m`, `v` is conjed.
044  
045    Example:
046    ```clojure
047    (append-if {:Value [1 2 3]} :Value 4)
048    ;; {:Value [1 2 3 4]}
049    ```"
050    [m k v]
051    (if (and (some? v) (keyword? k))
052      (let [new-v (ensure-vec v)]
053        (if-let [old-v (k m)]
054          (assoc m k (into [] (concat old-v new-v)))
055          (assoc m k new-v)))
056      m))
057  
058  (defn path->kw-vec
059    "Turns the path into a vector of keywords.
060  
061    Example:
062    ```clojure
063    (path->kw-vec \"a.b.c\")
064    ;; [:a :b :c]
065    ```"
066    [s]
067    {:pre [(string? s)]}
068    (mapv keyword (string/split s (re-pattern "\\."))))