Skip to content

Instantly share code, notes, and snippets.

@johanatan
Last active December 18, 2015 15:09
Embed
What would you like to do?
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