diff --git a/array.go b/array.go index 3eb3c3a..6917c7b 100644 --- a/array.go +++ b/array.go @@ -5,13 +5,15 @@ import ( ) // First() reduces the set of matched elements to the first in the set. -// It returns a new Selection object. +// It returns a new Selection object, and an empty Selection object if the +// the selection is empty. func (this *Selection) First() *Selection { return this.Eq(0) } // Last() reduces the set of matched elements to the last in the set. -// It returns a new Selection object. +// It returns a new Selection object, and an empty Selection object if +// the selection is empty. func (this *Selection) Last() *Selection { return this.Eq(-1) } @@ -24,6 +26,11 @@ func (this *Selection) Eq(index int) *Selection { if index < 0 { index += len(this.Nodes) } + + if index >= len(this.Nodes) || index < 0 { + return newEmptySelection(this.document) + } + return this.Slice(index, index+1) } diff --git a/array_test.go b/array_test.go index 13b6ca2..721affd 100644 --- a/array_test.go +++ b/array_test.go @@ -10,8 +10,8 @@ func TestFirst(t *testing.T) { } func TestFirstEmpty(t *testing.T) { - defer AssertPanic(t) - Doc().Find(".pvk-zzcontentzz").First() + sel := Doc().Find(".pvk-zzcontentzz").First() + AssertLength(t, sel.Nodes, 0) } func TestFirstRollback(t *testing.T) { @@ -31,6 +31,11 @@ func TestLast(t *testing.T) { } } +func TestLastEmpty(t *testing.T) { + sel := Doc().Find(".pvk-zzcontentzz").Last() + AssertLength(t, sel.Nodes, 0) +} + func TestLastRollback(t *testing.T) { sel := Doc().Find(".pvk-content") sel2 := sel.Last().End() @@ -53,6 +58,21 @@ func TestEqNegative(t *testing.T) { } } +func TestEqEmpty(t *testing.T) { + sel := Doc().Find("something_random_that_does_not_exists").Eq(0) + AssertLength(t, sel.Nodes, 0) +} + +func TestEqInvalidPositive(t *testing.T) { + sel := Doc().Find(".pvk-content").Eq(3) + AssertLength(t, sel.Nodes, 0) +} + +func TestEqInvalidNegative(t *testing.T) { + sel := Doc().Find(".pvk-content").Eq(-4) + AssertLength(t, sel.Nodes, 0) +} + func TestEqRollback(t *testing.T) { sel := Doc().Find(".pvk-content") sel2 := sel.Eq(1).End()