Last active
August 29, 2015 14:25
-
-
Save DayoOliyide/dfa6639b14f4e40de762 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; 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
commented
Jul 24, 2015
;; 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)))))
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
;; 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