Skip to content

Instantly share code, notes, and snippets.

@johanatan
Last active December 18, 2015 15:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johanatan/5802821 to your computer and use it in GitHub Desktop.
Save johanatan/5802821 to your computer and use it in GitHub Desktop.
Implementation of bash command line history stack in 20 lines of coffeescript. Some tricky corner cases are covered.
class CommandHistory
constructor: ->
@stack = []
@curPos = -1
@pushShouldReplaceLast = false
put = (index, cmd) =>
if @pushShouldReplaceLast then @stack[index..index] = cmd
else @stack.push cmd
@curPos = index
@pushShouldReplaceLast = false
move = (detectEnd, changePos, cur) =>
put @curPos, cur
if not detectEnd @curPos then changePos()
@pushShouldReplaceLast = @stack.length > 1 or @curPos < -1
@stack[@curPos..@curPos]
@back = _.partial move, ((pos) => pos is -@stack.length), => @curPos--
@forward = _.partial move, ((pos) => pos is -1), => @curPos++
@push = _.partial put, -1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment