Last active
October 18, 2015 17:25
-
-
Save myndzi/9e18a54223236ae20539 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
"use strict"; | |
function bagGenerator(pieces, exclusions) { | |
var buf = pieces.slice(), | |
size = pieces.length, | |
ptr = -1; | |
var shuffle = function () { | |
for (var t, j, i = 1; i < size; i++) { | |
j = Math.random() * (i+1) |0; | |
t = buf[i]; | |
buf[i] = buf[j]; | |
buf[j] = t; | |
} | |
ptr = size; | |
}; | |
shuffle(); | |
// as written, this will yield an infinite loop if all pieces | |
// in the 'pieces' array are also members of the 'exclusions' array | |
while (exclusions.indexOf(buf[size - 1]) > -1) { | |
buf.unshift(buf.pop()); | |
} | |
return function () { | |
var ret = buf[--ptr]; | |
if (!ptr) shuffle(); | |
return ret; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment