diff --git a/slist.go b/slist.go index dc27758..d339e90 100644 --- a/slist.go +++ b/slist.go @@ -40,6 +40,17 @@ func (seq *Slist) IsEmpty() bool { return seq.head == nil && seq.tail == nil // double check! } +// Return a slice with the elements of the list +func (seq *Slist) ToSlice() []interface{} { + + ret := make([]interface{}, 0, 4) + for it := NewIterator(seq); it.HasCurr(); it.Next() { + ret = append(ret, it.GetCurr()) + } + + return ret +} + func (seq *Slist) __append(item interface{}) *Slist { ptr := new(Snode) diff --git a/slist_test.go b/slist_test.go index 46d437f..7083286 100644 --- a/slist_test.go +++ b/slist_test.go @@ -1,6 +1,7 @@ package Slist import ( + "fmt" "github.com/stretchr/testify/assert" "testing" ) @@ -67,3 +68,15 @@ func TestSlist_RemoveFirst(t *testing.T) { assert.LessOrEqual(t, i, 3) } } + +func TestSlist_ToSlice(t *testing.T) { + + l := New(1, 2, 3) + s := l.ToSlice() + + for i, it := 0, NewIterator(l); it.HasCurr(); it.Next() { + assert.Equal(t, it.GetCurr().(int), s[i].(int)) + fmt.Printf("%d == %d\n", it.GetCurr().(int), s[i].(int)) + i++ + } +}