Created
October 8, 2013 12:54
-
-
Save ruslansavenok/6884232 to your computer and use it in GitHub Desktop.
Randomly slice an array and rearrange elements
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
/* | |
* Randomly slice an array and rearrange elements | |
* | |
* Useful for fake ajax data | |
* | |
* jQuery Example: | |
* $.get("/fake-ajax.json", function (data) { | |
* renderSomething(data.randomizeData()); | |
* }); | |
* | |
*/ | |
Array.prototype.randomizeData = function () { | |
function getRandomInt(min, max) { | |
return Math.floor(Math.random() * (max - min + 1) + min); | |
} | |
var arraySize = this.length; | |
var startSliceAt = getRandomInt(0, arraySize); | |
var endSliceAt = getRandomInt(startSliceAt, arraySize); | |
return this.slice(startSliceAt, endSliceAt).sort(function() {return 0.5 - Math.random()}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment