Advertisement
Guest User

Untitled

a guest
Jul 16th, 2014
270
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (ns some-namesace.blahblah
  2.   (:require [clojure.test :refer :all]
  3.             [some-other-namespace.blah.test-helper :refer [assert-equal]]
  4.             [clojure.string :as str]))
  5.  
  6. (defn- nesting-chain [expr] (re-seq #"[a-z]+|\[\]" expr))
  7.  
  8. (defn transform
  9.   [acc [chain v]]
  10.   (if (= (last chain) "[]")
  11.     (update-in acc (drop-last chain) concat [v])
  12.     ; by default, concat nil [v] will create sequences
  13.     ; if you really want vectors instead, replace the previous line by:
  14.     ; (update-in acc (drop-last chain) (comp (partial into []) concat) [v])
  15.     (assoc-in acc chain v)
  16.     ))
  17.  
  18. (defn parse-http-params
  19.   [s]
  20.   (->>
  21.    (str/split s #"&")
  22.    (map #(str/split % #"="))
  23.    (map #(vector (nesting-chain (first %)) (second %)))
  24.    (reduce transform {})))
  25.  
  26. (deftest test-asserts
  27.   (let [params-str "a[b][w][y]=3&a[c]=2&a[d][]=1&a[d][]=2&x[]=1&x[]=2&x[]=3"
  28.         expected { "a" {"b" { "w" { "y" "3" } } "c" "2" "d" ["1" "2"] } "x" ["1" "2" "3"] }]
  29.     (assert-equal expected (parse-http-params params-str))))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement