main
1// Copyright (c) 2015, Emir Pasic. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package arraylist
6
7import "github.com/emirpasic/gods/containers"
8
9// Assert Enumerable implementation
10var _ containers.EnumerableWithIndex = (*List)(nil)
11
12// Each calls the given function once for each element, passing that element's index and value.
13func (list *List) Each(f func(index int, value interface{})) {
14 iterator := list.Iterator()
15 for iterator.Next() {
16 f(iterator.Index(), iterator.Value())
17 }
18}
19
20// Map invokes the given function once for each element and returns a
21// container containing the values returned by the given function.
22func (list *List) Map(f func(index int, value interface{}) interface{}) *List {
23 newList := &List{}
24 iterator := list.Iterator()
25 for iterator.Next() {
26 newList.Add(f(iterator.Index(), iterator.Value()))
27 }
28 return newList
29}
30
31// Select returns a new container containing all elements for which the given function returns a true value.
32func (list *List) Select(f func(index int, value interface{}) bool) *List {
33 newList := &List{}
34 iterator := list.Iterator()
35 for iterator.Next() {
36 if f(iterator.Index(), iterator.Value()) {
37 newList.Add(iterator.Value())
38 }
39 }
40 return newList
41}
42
43// Any passes each element of the collection to the given function and
44// returns true if the function ever returns true for any element.
45func (list *List) Any(f func(index int, value interface{}) bool) bool {
46 iterator := list.Iterator()
47 for iterator.Next() {
48 if f(iterator.Index(), iterator.Value()) {
49 return true
50 }
51 }
52 return false
53}
54
55// All passes each element of the collection to the given function and
56// returns true if the function returns true for all elements.
57func (list *List) All(f func(index int, value interface{}) bool) bool {
58 iterator := list.Iterator()
59 for iterator.Next() {
60 if !f(iterator.Index(), iterator.Value()) {
61 return false
62 }
63 }
64 return true
65}
66
67// Find passes each element of the container to the given function and returns
68// the first (index,value) for which the function is true or -1,nil otherwise
69// if no element matches the criteria.
70func (list *List) Find(f func(index int, value interface{}) bool) (int, interface{}) {
71 iterator := list.Iterator()
72 for iterator.Next() {
73 if f(iterator.Index(), iterator.Value()) {
74 return iterator.Index(), iterator.Value()
75 }
76 }
77 return -1, nil
78}