Skip to content

Instantly share code, notes, and snippets.

@kolharsam
Last active May 27, 2020
Embed
What would you like to do?
Cassidy's Interview Question - 24/5
(def S (atom ""))
(def undo-stack (atom []))
(def redo-stack (atom []))
;; Helpers
(defn reset-stacks!
"Empties both stacks"
[]
(reset! undo-stack [])
(reset! redo-stack []))
(defn reset-app! []
(reset-stacks!)
(reset! S ""))
(defn update-stack
"Updates the stack with the latest state"
[st s]
(swap! st conj s))
(defn reset-stack
"Removes the top of st1 stack and moves it to the
st2 stack. Updates S with the current top of st1"
[st1 st2]
(if (empty? @st1)
(throw (Exception. "st1 is empty!"))
(let [top (last @st1)
new-st1 (vec (butlast @st1))
new-S top]
(update-stack st2 top)
(reset! st1 new-st1)
(reset! S new-S))))
;; Editor functions
(defn append
"Appends the text x to S"
[x]
(swap! S (partial apply str) x)
(update-stack undo-stack @S))
(defn delete
"Deletes last n characters of S"
[n]
(when (zero? n)
reset! S S)
(when (neg? n)
(throw (Exception. "Can't remove negative characters!")))
(let [current-S @S
new-S (subs current-S 0 (- (.length current-S) n))]
(reset! S new-S)
(update-stack undo-stack @S)))
(defn undo
"Reverts S to previous saved state"
[]
(reset-stack undo-stack redo-stack))
(defn redo
"Reverts undo"
[]
(reset-stack redo-stack undo-stack))
;; Playground
(reset-app!)
(append "this")
(append "isme")
(delete 3)
(delete 1)
(append "ismeeee!")
@S
(undo)
@undo-stack
@redo-stack
@S
(redo)
@undo-stack
@redo-stack
@S
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment