Last active
December 21, 2015 01:09
-
-
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.
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
| /** | |
| * 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