Last active
December 18, 2015 04:29
-
-
Save danro/5725790 to your computer and use it in GitHub Desktop.
Shuffle iterator js module.
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
var slots = iterator([80, 60, 50, 40, 20, 10], { shuffle: true, pool: 2 }); | |
var result = slots.next(); |
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
// -------------------------------------------------- | |
// Iterator with shuffle support | |
// -------------------------------------------------- | |
define(function (require) { | |
// dependencies | |
var _ = require('underscore'); | |
// default options | |
var defaults = { | |
repeat: true, | |
shuffle: false, | |
unique: true, | |
pool: 1 | |
}; | |
// iterator module function | |
function iterator(collection, options) { | |
// validate params | |
collection = _.toArray(collection); | |
options = _.extend({}, defaults, options); | |
if (options.pool < 1) options.pool = 1; | |
if (collection.length < options.pool) { | |
throw new Error('iterator: collection must be larger than pool.'); | |
} | |
// expose instance methods | |
var instance = { | |
list: [], | |
reset: function () { | |
var rest = this.list.slice(); | |
this.list = rest.concat(collection); | |
return this; | |
}, | |
skip: function (item) { | |
this.list = _.without(this.list, item); | |
this.validate(); | |
return this; | |
}, | |
validate: function () { | |
if (options.repeat && this.list.length < options.pool) this.reset(); | |
}, | |
hasNext: function () { | |
return this.list.length > 0; | |
}, | |
next: function () { | |
var result = this.list.shift(); | |
this.validate(); | |
return result; | |
} | |
}; | |
// override instance methods for shuffle | |
options.shuffle && _.extend(instance, { | |
reset: function () { | |
var rest = this.list.slice(); | |
if (options.unique) { | |
this.list = rest.concat(_.difference(_.shuffle(collection), rest)); | |
} else { | |
this.list = rest.concat(_.shuffle(collection)); | |
} | |
return this; | |
} | |
}); | |
// return instance with new list | |
return instance.reset(); | |
} | |
// return module (function) | |
return iterator; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment