From 7a3a4d1388c5f97d73a06021c1bd9167ea905656 Mon Sep 17 00:00:00 2001 From: bdistin Date: Fri, 4 May 2018 02:27:59 -0500 Subject: [PATCH] feat: add Collection#sweep() (#2528) --- src/client/Client.js | 9 +++------ src/util/Collection.js | 15 +++++++++++++++ 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/src/client/Client.js b/src/client/Client.js index b3aa6acf6c76..f685382d60b0 100644 --- a/src/client/Client.js +++ b/src/client/Client.js @@ -358,12 +358,9 @@ class Client extends BaseClient { if (!channel.messages) continue; channels++; - for (const message of channel.messages.values()) { - if (now - (message.editedTimestamp || message.createdTimestamp) > lifetimeMs) { - channel.messages.delete(message.id); - messages++; - } - } + messages += channel.messages.sweep( + message => now - (message.editedTimestamp || message.createdTimestamp) > lifetimeMs + ); } this.emit(Events.DEBUG, diff --git a/src/util/Collection.js b/src/util/Collection.js index 531f84d280f8..79cfc01109fe 100644 --- a/src/util/Collection.js +++ b/src/util/Collection.js @@ -259,6 +259,21 @@ class Collection extends Map { return Boolean(this.find(propOrFn, value)); } + /** + * Removes entries that satisfy the provided filter function. + * @param {Function} fn Function used to test (should return a boolean) + * @param {Object} [thisArg] Value to use as `this` when executing function + * @returns {number} The number of removed entries + */ + sweep(fn, thisArg) { + if (thisArg) fn = fn.bind(thisArg); + const previousSize = this.size; + for (const [key, val] of this) { + if (fn(val, key, this)) this.delete(key); + } + return previousSize - this.size; + } + /** * Identical to * [Array.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter),