diff --git a/README.md b/README.md index 78d1225..d437105 100644 --- a/README.md +++ b/README.md @@ -24,8 +24,9 @@ To run benchmarks, run this command in goquery's source directory: ## Changelog -* **v0.1.0** : Initial release. See [TODOs](#a1) for a list of upcoming features. +* **v0.2.0** : Add support for negative indices in Slice(). *Upcoming* : add jQuery's Closest() method. * **v0.1.1** : Add benchmarks to use as baseline for refactorings, refactor Next...() and Prev...() methods to use the new html package's linked list features (Next/PrevSibling, FirstChild). Good performance boost (40+% in some cases). +* **v0.1.0** : Initial release. See [TODOs](#a1) for a list of upcoming features. ## API @@ -93,7 +94,6 @@ Taken from example_test.go: * Add jQuery's `Closest()`? Other missing functions? -* Support negative indices in `Slice()`, like jQuery. ## License diff --git a/array.go b/array.go index 412f027..3e76244 100644 --- a/array.go +++ b/array.go @@ -30,7 +30,12 @@ func (this *Selection) Eq(index int) *Selection { // Slice() reduces the set of matched elements to a subset specified by a range // of indices. At the moment, negative indices are not supported. func (this *Selection) Slice(start int, end int) *Selection { - // TODO : Negative indices, like jQuery + if start < 0 { + start += len(this.Nodes) + } + if end < 0 { + end += len(this.Nodes) + } return pushStack(this, this.Nodes[start:end]) } diff --git a/array_test.go b/array_test.go index 8f3c077..599d88e 100644 --- a/array_test.go +++ b/array_test.go @@ -70,6 +70,31 @@ func TestSliceOutOfBounds(t *testing.T) { Doc().Root.Find(".pvk-content").Slice(2, 12) } +func TestNegativeSliceStart(t *testing.T) { + sel := Doc().Root.Find(".container-fluid").Slice(-2, 3) + AssertLength(t, sel.Nodes, 1) + AssertSelectionIs(t, sel.Eq(0), "#cf3") +} + +func TestNegativeSliceEnd(t *testing.T) { + sel := Doc().Root.Find(".container-fluid").Slice(1, -1) + AssertLength(t, sel.Nodes, 2) + AssertSelectionIs(t, sel.Eq(0), "#cf2") + AssertSelectionIs(t, sel.Eq(1), "#cf3") +} + +func TestNegativeSliceBoth(t *testing.T) { + sel := Doc().Root.Find(".container-fluid").Slice(-3, -1) + AssertLength(t, sel.Nodes, 2) + AssertSelectionIs(t, sel.Eq(0), "#cf2") + AssertSelectionIs(t, sel.Eq(1), "#cf3") +} + +func TestNegativeSliceOutOfBounds(t *testing.T) { + defer AssertPanic(t) + Doc().Root.Find(".container-fluid").Slice(-12, -7) +} + func TestSliceRollback(t *testing.T) { sel := Doc().Root.Find(".pvk-content") sel2 := sel.Slice(0, 2).End()