Created
June 3, 2011 18:02
-
-
Save carlosrberto/1006807 to your computer and use it in GitHub Desktop.
jQuery Random
This file contains 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
// 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