Skip to content

Instantly share code, notes, and snippets.

@DayoOliyide
Last active August 29, 2015 14:25
Show Gist options
  • Save DayoOliyide/dfa6639b14f4e40de762 to your computer and use it in GitHub Desktop.
Save DayoOliyide/dfa6639b14f4e40de762 to your computer and use it in GitHub Desktop.
;; Write a function that takes a string and does a partial replacement on the string.
;; By partial replacement, I mean if the string is 3 characters or more replace all the
;; characters (except the first and last with X), if the string is less than 3 replace
;; with all characters with X
;; E.g
;; (partial-replacement "IamASecretPassword") => "IXXXXXXXXXXXXXXXXd"
;; (partial-replacement "YES") => "YXS"
;; (partial-replacement "NO") => "XX"
(defn partial-replacement [s]
;;TODO .. code me ... code me
)
(require '[clojure.test :refer [testing is]])
(defn ohh-tdd []
(testing "Testing partial-replacement"
(testing "Testing a few :) paths"
(is (= "sXXXXXXXXXXXXXt" (partial-replacement "shhh!itsasecret")))
(is (= "oXXXXXXXXe" (partial-replacement "opensesame")))
(is (= "YXS" (partial-replacement "YES")))
)
(testing "Testing a few :( paths"
(is (= nil (partial-replacement nil)))
(is (= "" (partial-replacement "")))
(is (= "XX" (partial-replacement "NO")))
(is (= "X" (partial-replacement "o")))
)
)
)
(ohh-tdd)
@hookercookerman
Copy link

(defn partial-replacement
  [s]
  (cond
    (nil? s) nil
    (< (count s) 3) (clojure.string/replace s #"." "X")
    :else
    (clojure.string/replace s #"^(.)(.+)(.)$"
                            (fn [[_ a b c]]
                              (let [conv (clojure.string/replace b #"." "X")]
                                (apply str a conv c))))))

@DayoOliyide
Copy link
Author

;; didn't know you could use functions for the replacement/match arguments for the
;; clojure.string/replace function .....I've learnt something new.

;; I think the else bit could be rewritten to be a bit clearer
(defn partial-replacement
  [s]
  (cond
    (nil? s) nil
    (< (count s) 3) (clojure.string/replace s #"." "X")
    :else
    (let [length (- (count s) 2)
          replaced (clojure.string/join (repeat length \X))]
      (str (first s) replaced (last s)))))

@hookercookerman
Copy link

thanks for edit lol yeah my function on the replace is a bit funky; I much prefer the str approach not sure what I was thinking. cheers

@neilwashere
Copy link

;; I was thinking of a pure regex way to do this as a one liner. Didn't quite get there. Got this ugly mofo on the go though:

(defn partial-replacement [s]
  (if (empty? s)
    s
    (let [match (first (remove nil? (rest (re-matches #"^(.{1,2})$|^.(.+).$" s))))]
      (clojure.string/replace-first s (re-pattern match) #(clojure.string/join (repeat (count %1) \X))))))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment