Skip to content

Instantly share code, notes, and snippets.

@jaytaph
Last active December 14, 2015 03:49
Show Gist options
  • Save jaytaph/5023620 to your computer and use it in GitHub Desktop.
Save jaytaph/5023620 to your computer and use it in GitHub Desktop.
/**
* Returns an iterator object. Must be implemented to work with foreach etc.
*/
interface iterable {
public method __iterator();
}
/**
* Actual iterator interface
*/
interface iterator {
// Rewinds the iterator back to the first element
public method __rewind();
// Returns a tuple with all items for the current element
public method __current();
// Move the internal pointer to the next element
public method __next();
// Returns true when there is a next element, false otherwise
public method __hasNext();
}
/**
* Iterator that implements backward iteration as well
*/
interface bidirectionalIterator implements iterator {
// Move iternal pointer to the previous element
public method __prev();
// Returns true when there is a previous element, false otherwise
public method __hasPrev();
}
/**
* Implements a lenght() method that will return the length of the iterator. Only usefull for iterators where the
* number of elements are known in advance.
*/
interface rangeIterator implements iterator {
public method __length();
}
/**
*
*/
class arrayIterator implements iterable, rangeIterator {
protected property items; // Hash with iterable items
protected property keys; // List of keys (so we can fetch the Nth index without knowing the key)
protected property idx = 0; // internal iterator pointer
public method __ctor(hash items) {
self.items = items;
self.keys = items.__keys();
self._idx = 0;
}
/**
* This class does not have an external iterator, but implements an iterator in itself
*/
public method __getIterator() {
return self;
}
public method __rewind() {
self._idx = 0;
}
public method __current() {
return tuple[
self.keys[self.idx],
self.items[self.keys[self.idx]]
];
}
public method __next() {
self.idx++;
}
public method __hasNext() {
return self.idx < self.keys.__length() - 1;
}
public method __length() {
return self.keys.__length();
}
}
foo = arrayIterator(hash["foo":1, "bar":"baz", true:false]);
foreach (foo as k,v,meta) {
if (meta.first) io.printf("First item!\n");
if (meta.last) io.printf("Last item!\n");
io.printf("Item %d of %d: %s => %s\n", meta.index, meta.count, k, v);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment