Skip to content

Commit

Permalink
feat(skiplist): iterator
Browse files Browse the repository at this point in the history
  • Loading branch information
houz42 committed Dec 25, 2023
1 parent c085383 commit 3c21759
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
30 changes: 30 additions & 0 deletions skiplists/example_iter_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
//go:build goexperiment.rangefunc

package skiplists_test

import (
"fmt"

"github.com/houz42/abstract/skiplists"
)

func ExampleSkipList_All() {
list := skiplists.New[string]()

list.Insert("Hello")
list.Insert("gopher")
list.Insert("Go")
list.Insert("is")
list.Insert("fun")

for i, v := range list.All() {
fmt.Println(i, v)
}

// Output:
// 0 Go
// 1 Hello
// 2 fun
// 3 gopher
// 4 is
}
20 changes: 20 additions & 0 deletions skiplists/skiplists_iter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
//go:build goexperiment.rangefunc

package skiplists

import "iter"

// All returns an iterator that yields all the ordered elements in the SkipList.
func (sl *SkipList[V]) All() iter.Seq2[int, V] {
return func(yield func(int, V) bool) {
node := sl.head.next[0]
i := 0
for node != nil {
if !yield(i, node.val) {
return
}
i++
node = node.next[0]
}
}
}

0 comments on commit 3c21759

Please sign in to comment.