From f456f4c3c0e101c13c507534117d600acda60c3d Mon Sep 17 00:00:00 2001 From: SpaceEEC Date: Fri, 25 May 2018 16:49:10 +0200 Subject: [PATCH] feat(Collection): backport partition method Commit: a732402c95438f5ddda20958e5c1b2360500069a PR: #2511 --- src/util/Collection.js | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/util/Collection.js b/src/util/Collection.js index 7f0cb9dfa..1b085a110 100644 --- a/src/util/Collection.js +++ b/src/util/Collection.js @@ -308,6 +308,27 @@ class Collection extends Map { return results; } + /** + * Partitions the collection into two collections where the first collection + * contains the items that passed and the second contains the items that failed. + * @param {Function} fn Function used to test (should return a boolean) + * @param {*} [thisArg] Value to use as `this` when executing function + * @returns {Collection[]} + * @example const [big, small] = collection.partition(guild => guild.memberCount > 250); + */ + partition(fn, thisArg) { + if (typeof thisArg !== 'undefined') fn = fn.bind(thisArg); + const results = [new Collection(), new Collection()]; + for (const [key, val] of this) { + if (fn(val, key, this)) { + results[0].set(key, val); + } else { + results[1].set(key, val); + } + } + return results; + } + /** * Identical to * [Array.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map).