Autonomous Machine

Cycle.js: A JavaScript implementation of Rail's text helper

On a recent project I had to zebra-stripe a table on the client side in JavaScript, and set out to port Rail's cycle text helper to JavaScript. I rewrote it a couple weeks later using what Douglas Crockford calls the module pattern.

var Cycle = function(){
    var cycles, that, thru, reset;
    
    cycles = {};
    that = {};
 
    thru = function(){
        var values, i, cycle, options, name, nextValue;
 
        values = Array.prototype.slice.call(arguments);
        options = typeof(values.slice(-1)[0]) === 'object' ? values.pop() : {};
 
        name = options['name'] || 'default';
 
        if(!cycles[name]) {
            cycles[name] = {
              values: values,
              index: 0
            };
        };
        cycle = cycles[name];
        nextValue = cycle.values[cycle.index];
        cycle.index = (cycle.index === cycle.values.length -1) ? 0 : (cycle.index +1);
        return nextValue;
    };
    that.thru = thru;
 
    reset = function(name) {
        if(cycles[name]) {
            cycles[name].index = 0;
        }
    };
    that.reset = reset;
    
    return that;
 
}();

Usage is fairly simple:

>>> Cycle.thru('one', 'two');
"one"
>>> Cycle.thru('one', 'two');
"two"
>>> Cycle.thru('one', 'two');
"one"

Passing an object literal containing a name property allows for reset functionality:

>>> Cycle.thru('one', 'two', 'three', {name: 'numbers'});
"one"
>>> Cycle.thru('one', 'two', 'three', {name: 'numbers'});
"two"
>>> Cycle.reset('numbers');
>>> Cycle.thru('one', 'two', 'three', {name: 'numbers'});
"one"

I've started a GitHub repository for this and other small Javascript utility functions.