Counting, repeating, and unique ids
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 ' + (i ' );
} );
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( '
‘ + i + ‘: ‘ + $.newDateValue() + ‘
‘ );
} )
.times( function( i ) {
$( ‘body’ ).append( ‘
‘ + i + ‘: ‘ + Number(new Date()) + ‘
‘ );
} );
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( '‘ + k.next() + ‘ ‘ );
} );
$.repeat(1).times( function() {
$( ‘body’ ).append( ‘‘ + k.current() + ‘ ‘ );
} );
k.init( null, -2 );
$.repeat(3).times( function() {
$( ‘body’ ).append( ‘‘ + k.next() + ‘ ‘ );
} );



Subscribe by RSS