add Get() to array.go, with tests

This commit is contained in:
Martin Angers
2012-08-30 15:52:41 -04:00
parent 5608755eb5
commit fe36d7039a
4 changed files with 42 additions and 42 deletions

View File

@@ -1,5 +1,9 @@
package goquery
import (
"exp/html"
)
// First() reduces the set of matched elements to the first in the set.
// It returns a new Selection object.
func (this *Selection) First() *Selection {
@@ -16,10 +20,8 @@ func (this *Selection) Last() *Selection {
// If a negative index is given, it counts backwards starting at the end of the set.
// It returns a new Selection object, and an empty Selection object if the index is invalid.
func (this *Selection) Eq(index int) *Selection {
var l = len(this.Nodes)
if index < 0 {
index += l
index += len(this.Nodes)
}
return this.Slice(index, index+1)
}
@@ -29,3 +31,13 @@ func (this *Selection) Eq(index int) *Selection {
func (this *Selection) Slice(start int, end int) *Selection {
return pushStack(this, this.Nodes[start:end])
}
// Get() retrieves the underlying node at the specified index.
// Get() without parameter is not implemented, since the node array is available
// on the Selection object.
func (this *Selection) Get(index int) *html.Node {
if index < 0 {
index += len(this.Nodes) // Negative index gets from the end
}
return this.Nodes[index]
}

View File

@@ -66,3 +66,30 @@ func TestSliceOutOfBounds(t *testing.T) {
}()
doc.Find(".pvk-content").Slice(2, 12)
}
func TestGet(t *testing.T) {
sel := doc.Find(".pvk-content")
node := sel.Get(1)
if sel.Nodes[1] != node {
t.Errorf("Expected node %v to be %v.", node, sel.Nodes[1])
}
}
func TestGetNegative(t *testing.T) {
sel := doc.Find(".pvk-content")
node := sel.Get(-3)
if sel.Nodes[0] != node {
t.Errorf("Expected node %v to be %v.", node, sel.Nodes[0])
}
}
func TestGetInvalid(t *testing.T) {
defer func() {
if e := recover(); e == nil {
t.Error("Expected a panic, Get() called with out of bounds index.")
}
}()
sel := doc.Find(".pvk-content")
sel.Get(129)
}

18
get.go
View File

@@ -1,18 +0,0 @@
package goquery
import (
"exp/html"
)
// Get() without parameter is not implemented, its behaviour would be exactly the same as getting selection.Nodes
func (this *Selection) Get(index int) *html.Node {
var l = len(this.Nodes)
if index < 0 {
index += l // Negative index gets from the end
}
if index >= 0 && index < l {
return this.Nodes[index]
}
return nil
}

View File

@@ -1,21 +0,0 @@
package goquery
import (
"testing"
)
func TestGet(t *testing.T) {
sel := doc.Find(".pvk-content")
node := sel.Get(1)
if sel.Nodes[1] != node {
t.Errorf("Expected node %v to be %v.", node, sel.Nodes[1])
}
node = sel.Get(-3)
if sel.Nodes[0] != node {
t.Errorf("Expected node %v to be %v.", node, sel.Nodes[0])
}
node = sel.Get(129)
if node != nil {
t.Error("Expected node to be nil.")
}
}