]> Cypherpunks repositories - gostls13.git/commitdiff
add a trivial visitor method, just for fun
authorRob Pike <r@golang.org>
Fri, 6 Feb 2009 22:32:09 +0000 (14:32 -0800)
committerRob Pike <r@golang.org>
Fri, 6 Feb 2009 22:32:09 +0000 (14:32 -0800)
R=gri
DELTA=31  (30 added, 1 deleted, 0 changed)
OCL=24568
CL=24575

src/lib/container/array/array.go
src/lib/container/array/array_test.go

index 768e46d3a46cf6ec9fce4a55cd978e5d26bb55a6..e29736fb6506cde9c55ffe60d9d4184844200cfa 100644 (file)
@@ -140,6 +140,13 @@ func (p *Array) Slice(i, j int) *Array {
 }
 
 
+func (p *Array) Do(f func(elem Element)) {
+       for i := 0; i < len(p.a); i++ {
+               f(p.a[i])       // not too safe if f changes the Array
+       }
+}
+
+
 // Convenience wrappers
 
 func (p *Array) Push(x Element) {
index df9fee673c006fb5f9174e4f78126e6ebbc92800..43ac702abc0493fd34479733f522f9d725e34fda 100644 (file)
@@ -139,7 +139,6 @@ func TestInsertArray(t *testing.T) {
        verify_pattern(t, a, 8, 1000, 2);
 }
 
-
 func TestSorting(t *testing.T) {
        const n = 100;
        a := array.NewIntArray(n);
@@ -148,3 +147,26 @@ func TestSorting(t *testing.T) {
        }
        if sort.IsSorted(a) { t.Error("not sorted") }
 }
+
+
+func TestDo(t *testing.T) {
+       const n = 25;
+       const salt = 17;
+       a := array.NewIntArray(n);
+       for i := 0; i < n; i++ {
+               a.Set(i, salt * i);
+       }
+       count := 0;
+       a.Do(
+               func(e array.Element) {
+                       i := e.(int);
+                       if i != count*salt {
+                               t.Error("value at", count, "should be", count*salt, "not", i)
+                       }
+                       count++;
+               }
+       );
+       if count != n {
+               t.Error("should visit", n, "values; did visit", count)
+       }
+}