Last active
August 29, 2015 14:00
-
-
Save jtpaasch/bd3b5f32af5eff046030 to your computer and use it in GitHub Desktop.
A simple tool for yielding items incrementally from a list.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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