Advertisement
Guest User

Untitled

a guest
May 8th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (ns hello-test.core
  2.   (:require [clojure.spec.alpha :as s])
  3.   (:require [clojure.string :as str]))
  4.  
  5. (def pattern "host(twitter) path(?user/user/?id) queryparam(offset=?offset)")
  6.  
  7. (defn pattern-to-map [str-pattern]
  8.   (let [[_ command pattern] (re-matches #"(?i)(\w+)\(([A-Za-z0-9\/\?]+)\)" str-pattern)]
  9.     {:command (keyword command) :pattern pattern}))
  10.  
  11. (defn scramble-url [url]
  12.   (let [url-pattern #"(?:http[s]?:\/\/)?(?:www\.)?([A-Za-z#.]+)\.(?:\w+)(?:\/?)((?:[A-Za-z\-0-9\.]+(?:\/)?)*)\??((?:(?:\w+)=(?:\w+)&?)*)"        
  13.         [_ host path params] (re-matches url-pattern url)
  14.         query-map (map #(str/split % #"=") (str/split params #"&"))]
  15.     {:host host :path path :params query-map}))
  16.  
  17. (scramble-url "http://twitter.com?t=3&a=5")
  18.  
  19. (defn build-path-component [pattern-comp url-comp]
  20.   (if (= (first pattern-comp) \?)
  21.     {:type :path-param :result [(keyword (apply str (rest pattern-comp))) url-comp] }
  22.     {:type :path-match :result (= pattern-comp url-comp) }))
  23.  
  24. (defn get-path [pattern path]
  25.   (let [paths-compnents (str/split path #"/")
  26.         pattern-compnents (str/split pattern #"/")
  27.         mapped (map build-path-component pattern-compnents paths-compnents)
  28.         res (every? true? (map :result (filter #(= (:type %) :path-match) mapped)))]        
  29.         (when (and (true? res) (= (count paths-compnents) (count pattern-compnents)))
  30.           (map :result (filter #(= (:type %) :path-param) mapped)))))
  31.  
  32. (get-path "?user/user/?id" "vlad/user/12")
  33.  
  34. (defn get-queryparams [pattern url-queryparams]
  35.   (let [[name key] (str/split pattern #"=")
  36.         url-param (->> url-queryparams
  37.                        (filter #(= name (first %)))
  38.                        (first))]
  39.         { (keyword (apply str (rest key))) (second url-param) }))
  40.  
  41. (get-queryparams "list=?type" [["list" 5]])
  42.  
  43. (defn match-by-command [cmd url]
  44.   (let [command (:command cmd)
  45.         pattern (:pattern cmd)
  46.         url-info (scramble-url url)]
  47.       (cond
  48.         (= command :host) (when (= (:host url-info) pattern)
  49.                             {:host pattern})
  50.         :else nil)))
  51.  
  52. (println (map #(pattern-to-map %) (str/split pattern #" ")))
  53.  
  54. ;(remove #(= (:id %1) 1) `({:id 1 :topic "tt"} {:id 2 :topic "tt"}))
  55.  
  56. ;(merge-with #(+ %1 %2) {:a 1, :b 2} {:a 1})
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement