Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (ns hello-test.core
- (:require [clojure.spec.alpha :as s])
- (:require [clojure.string :as str]))
- (def pattern "host(twitter) path(?user/user/?id) queryparam(offset=?offset)")
- (defn pattern-to-map [str-pattern]
- (let [[_ command pattern] (re-matches #"(?i)(\w+)\(([A-Za-z0-9\/\?]+)\)" str-pattern)]
- {:command (keyword command) :pattern pattern}))
- (defn scramble-url [url]
- (let [url-pattern #"(?:http[s]?:\/\/)?(?:www\.)?([A-Za-z#.]+)\.(?:\w+)(?:\/?)((?:[A-Za-z\-0-9\.]+(?:\/)?)*)\??((?:(?:\w+)=(?:\w+)&?)*)"
- [_ host path params] (re-matches url-pattern url)
- query-map (map #(str/split % #"=") (str/split params #"&"))]
- {:host host :path path :params query-map}))
- (scramble-url "http://twitter.com?t=3&a=5")
- (defn build-path-component [pattern-comp url-comp]
- (if (= (first pattern-comp) \?)
- {:type :path-param :result [(keyword (apply str (rest pattern-comp))) url-comp] }
- {:type :path-match :result (= pattern-comp url-comp) }))
- (defn get-path [pattern path]
- (let [paths-compnents (str/split path #"/")
- pattern-compnents (str/split pattern #"/")
- mapped (map build-path-component pattern-compnents paths-compnents)
- res (every? true? (map :result (filter #(= (:type %) :path-match) mapped)))]
- (when (and (true? res) (= (count paths-compnents) (count pattern-compnents)))
- (map :result (filter #(= (:type %) :path-param) mapped)))))
- (get-path "?user/user/?id" "vlad/user/12")
- (defn get-queryparams [pattern url-queryparams]
- (let [[name key] (str/split pattern #"=")
- url-param (->> url-queryparams
- (filter #(= name (first %)))
- (first))]
- { (keyword (apply str (rest key))) (second url-param) }))
- (get-queryparams "list=?type" [["list" 5]])
- (defn match-by-command [cmd url]
- (let [command (:command cmd)
- pattern (:pattern cmd)
- url-info (scramble-url url)]
- (cond
- (= command :host) (when (= (:host url-info) pattern)
- {:host pattern})
- :else nil)))
- (println (map #(pattern-to-map %) (str/split pattern #" ")))
- ;(remove #(= (:id %1) 1) `({:id 1 :topic "tt"} {:id 2 :topic "tt"}))
- ;(merge-with #(+ %1 %2) {:a 1, :b 2} {:a 1})
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement