Skip to content

Commit

Permalink
feat: add Collection#sweep() (#2528)
Browse files Browse the repository at this point in the history
  • Loading branch information
bdistin authored and Lewdcario committed May 4, 2018
1 parent 32369f3 commit 7a3a4d1
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 deletions.
9 changes: 3 additions & 6 deletions src/client/Client.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
15 changes: 15 additions & 0 deletions src/util/Collection.js
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down

0 comments on commit 7a3a4d1

Please sign in to comment.