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)]
028        (assoc m kw (ensure-vec v))
029        m)))
030  
031  (defn replace-if
032    "Replaces `v`alue of `k`ey in struct if `v`is not `nil`.
033  
034    Example:
035    ```clojure
036    (replace-if {:Type \"a\"} :Type \"b\")
037    ;; {:Type \"b\"}
038    ```
039    "
040    [m k v]
041    (if (and (some? v) (keyword? k)) (assoc m k v) m))
042  
043  (defn append-if
044    "Appends `v` to the value of `k`. If `k` does not exist in `m`,
045    `k [v]` is assoced.  If `k` does exist in `m`, `v` is conjed.
046  
047    Example:
048    ```clojure
049    (append-if {:Value [1 2 3]} :Value 4)
050    ;; {:Value [1 2 3 4]}
051    ```"
052    [m k v]
053    (if (and (some? v) (keyword? k))
054      (let [new-v (ensure-vec v)]
055        (if-let [old-v (k m)]
056          (assoc m k (into [] (concat old-v new-v)))
057          (assoc m k new-v)))
058      m))
059  
060  (defn path->kw-vec
061    "Turns the path into a vector of keywords.
062  
063    ```clojure
064    (path->kw-vec \"a.b.c\")
065    ;; [:a :b :c]
066    ```"
067    [s]
068    {:pre [(string? s)]}
069    (into []
070          (map
071           keyword
072           (string/split s (re-pattern "\\.")))))