Skip to content

Instantly share code, notes, and snippets.

@sug0
Created February 17, 2018 04:34
Show Gist options
  • Save sug0/81af28f57f7f16f944bd81885d10ece6 to your computer and use it in GitHub Desktop.
Save sug0/81af28f57f7f16f944bd81885d10ece6 to your computer and use it in GitHub Desktop.
A Zipper in Go using "container/list" | https://en.wikipedia.org/wiki/Zipper_(data_structure)
package zipper
import l "container/list"
type Zipper struct {
nzip int
list *l.List
back *l.Element
sel *l.Element
front *l.Element
}
func New(list *l.List) *Zipper {
z := new(Zipper)
z.nzip = 0
z.list = list
z.sel = list.Front()
z.back = z.sel.Prev()
z.front = z.sel.Next()
return z
}
func (z *Zipper) Zip() *Zipper {
if z.front != nil {
z.sel = z.sel.Next()
z.back = z.sel.Prev()
z.front = z.sel.Next()
z.nzip++
return z
}
return nil
}
func (z *Zipper) Unzip() *Zipper {
if z.back != nil {
z.sel = z.sel.Prev()
z.back = z.sel.Prev()
z.front = z.sel.Next()
z.nzip--
return z
}
return nil
}
func (z *Zipper) Len() int {
return z.list.Len()
}
func (z *Zipper) LenZipped() int {
return z.nzip
}
func (z *Zipper) LenUnzipped() int {
return z.Len() - z.LenZipped()
}
func (z *Zipper) Top() *l.Element {
return z.sel
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment