Skip to content

Instantly share code, notes, and snippets.

@amacdougall
Last active December 21, 2015 01:09
Show Gist options
  • Select an option

  • Save amacdougall/6226056 to your computer and use it in GitHub Desktop.

Select an option

Save amacdougall/6226056 to your computer and use it in GitHub Desktop.
Underscore mixin which rejects items from a list if too many of them match the iterator function. Keeps all other list items.
/**
* Rejects items which match the iterator, beyond the threshold. Accepts all other items.
*
* Example: _([1, 1, 1, 1, 2]).limitQuantity(2, function(n) {return n == 1;}); // [1, 1, 2]
*
* @param list The list to be filtered. Omitted in OO-style (i.e. _(list).limitQuantity).
* @param n The number of matching items to be allowed.
* @param f The filter function against which list items will be matched.
*/
_.limitQuantity || _.mixin({
limitQuantity: function(list, n, f) {
var observed = 0;
return _(list).reduce(function(result, item) {
if (f(item)) {
observed += 1;
if (observed <= n) {
result.push(item);
}
} else {
result.push(item);
}
return result;
}, []);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment