Skip to content

Instantly share code, notes, and snippets.

@adam-singer
Created January 10, 2012 02:08
Show Gist options
  • Save adam-singer/1586382 to your computer and use it in GitHub Desktop.
Save adam-singer/1586382 to your computer and use it in GitHub Desktop.
Example of a possible extension of List to include a indexesOf method.
class ListExtension {
/**
* Returns a [List] of indexes of the given [element], starting
* the search at index [startIndex] to [endIndex] (exclusive).
* Returns an empty [List] if [element] is not found.
*/
static List<num> indexesOf(List list, Object element, int startIndex, int endIndex) {
List<num> n = new List<num>();
if (startIndex >= list.length) {
return n;
}
if (startIndex < 0) {
startIndex = 0;
}
for (int i = startIndex; i < endIndex; i++) {
if (list[i] == element) {
n.add(i);
}
}
return n;
}
}
void main() {
void run() {
List<num> l = new List<num>();
l.add(10);
l.add(20);
l.add(10);
l.add(30);
List<num> e = ListExtension.indexesOf(l, 10, 0, l.length);
Expect.equals(2, e.length);
Expect.equals(0, e[0]);
Expect.equals(2, e[1]);
}
run();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment