Skip to content

Instantly share code, notes, and snippets.

@carlosrberto
Created June 3, 2011 18:02
Show Gist options
  • Save carlosrberto/1006807 to your computer and use it in GitHub Desktop.
Save carlosrberto/1006807 to your computer and use it in GitHub Desktop.
jQuery Random
// retorna um range de numeros, ex: range(0, 3) -> [0,1,2,3]
function rangeNumbers(a, b){
var arr = [];
while(a<=b){
arr.push(a);
a++;
}
return arr;
}
// remove um item do array pelo seu valor
function removeItem(arr, item){
var index, al, ar;
index = arr.indexOf(item);
al = arr.slice(0, index);
ar = arr.slice(index+1, arr.length);
return index != -1 ? al.concat(ar) : ar;
}
// um numero randomico unico
function uniqueRandom(arr){
var o_arr = arr;
if ( !! uniqueRandom.cache[arr] ) arr = uniqueRandom.cache[arr];
var rn = Math.floor(Math.random() * arr.length);
var ritem = arr[rn];
var index = arr.indexOf(rn);
uniqueRandom.cache[o_arr] = removeItem(arr, ritem);
console.log(o_arr, uniqueRandom.cache[o_arr]);
return ritem;
}
uniqueRandom.cache = {}
jQuery.jQueryRandom = 0;
//seletor jquery para retornar de uma coleção de elementos, elementos unicos
jQuery.extend(jQuery.expr[":"],
{
random: function(a, i, m, r) {
var arr = rangeNumbers(0, r.length-1);
if (i == 0) {
jQuery.jQueryRandom = uniqueRandom(arr);
};
return i == jQuery.jQueryRandom;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment