Skip to content

Instantly share code, notes, and snippets.

@jtpaasch
Last active August 29, 2015 14:00
Show Gist options
  • Save jtpaasch/bd3b5f32af5eff046030 to your computer and use it in GitHub Desktop.
Save jtpaasch/bd3b5f32af5eff046030 to your computer and use it in GitHub Desktop.
A simple tool for yielding items incrementally from a list.
/**
* A tool for yielding items incrementally from a list.
* Usage:
* var gen = Generator([1, 2, 3], 0);
* gen.next(); // Yields 1
* gen.next(); // Yields 2
* gen.previous(); // Yields 1
*
* @author JT Paasch
* @license MIT <http://opensource.org/licenses/MIT>
*/
var Generator = function(list, initial_index) {
/**
* The current index.
* @var Integer
*/
var index;
/**
* The value to yield.
* @var Mixed
*/
var yield_value;
// Initialize the index, or throw an error if the index is invalid.
if (list[initial_index] === undefined) {
throw "No index '" + initial_index + "' in list: " + list;
} else {
index = initial_index;
}
/**
* Yield the next value in the list (if it exists).
* @return Mixed The value, or undefined.
*/
var next = function() {
yield_value = undefined;
if (list[index + 1] !== undefined) {
yield_value = list[index + 1];
index += 1;
}
return yield_value;
};
/**
* Yield the previous value in the list (if it exists).
* @return Mixed The value, or undefined.
*/
var previous = function() {
yield_value = undefined;
if (list[index - 1] !== undefined) {
yield_value = list[index - 1];
index -= 1;
}
return yield_value;
};
/**
* Return public methods.
* @return Object
*/
return {
next: next,
previous: previous
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment