Here are some micro jQuery plugins that implement JavaScript closures, for object oriented pleasure.
Repeat Something n Times
/**
* Repeat something n times
*/
$.repeat = function( n ) {
return {
times: function( something ) {
for( var i = 0; i < n; i++ ) {
something( i );
}
return this;
}
}
};
/*
* Example: hip hip hurrah
*/
$.repeat(3).times( function( i ) {
$( 'body' ).append( '<span>' + (i < 2 ? "hip" : "hurrah") + ' </span>' );
} );
New Date Value (unique id)
/**
* Return a new date value
*
* Each call returns a value greater than the previous call
*/
$.newDateValue = (function() {
var current = 0;
return function() {
do {
var d = Number(new Date());
}
while( current == d );
return (current = d);
}
})();
/*
* Example: 4 unique ids, and 4 not unique
*/
$.repeat(4)
.times( function( i ) {
$( 'body' ).append( '<div>' + i + ': ' + $.newDateValue() + '</div>' );
} )
.times( function( i ) {
$( 'body' ).append( '<div>' + i + ': ' + Number(new Date()) + '</div>' );
} );
Counter
/**
* Return a counter with three methods: next, current, and init
*/
$.counter = function() {
var current = 0;
var increment = 1;
return {
/**
* Initialize current value and increment
*/
init: function( c, i ) {
var newCurrent = parseInt( c, 10 );
if (! isNaN( newCurrent )) {
current = newCurrent;
}
var newIncrement = parseInt( i, 10 );
if (! isNaN( newIncrement )) {
increment = newIncrement;
}
return this;
}
/**
* Get the next value
*/
, next: function() {
return current += increment;
}
/**
* Get the current value
*/
, current: function() {
return current;
}
}
};
/*
* Example: 1 2 3 3 1 -1 -3
*/
var k = $.counter();
$.repeat(3).times( function() {
$( 'body' ).append( '<span>' + k.next() + ' </span>' );
} );
$.repeat(1).times( function() {
$( 'body' ).append( '<span>' + k.current() + ' </span>' );
} );
k.init( null, -2 );
$.repeat(3).times( function() {
$( 'body' ).append( '<span>' + k.next() + ' </span>' );
} );