diff --git a/src/util/Collection.js b/src/util/Collection.js index 5e45c968f..8477404f7 100644 --- a/src/util/Collection.js +++ b/src/util/Collection.js @@ -1,3 +1,5 @@ +const util = require('util'); + /** * A Map with additional utility methods. This is used throughout discord.js rather than Arrays for anything that has * an ID, for significantly improved performance and ease-of-use. @@ -458,4 +460,59 @@ class Collection extends Map { } } +/** + * Searches for all items where their specified property's value is identical to the given value + * (`item[prop] === value`). + * @param {string} prop The property to test against + * @param {*} value The expected value + * @returns {Array} + * @deprecated + * @example + * collection.findAll('username', 'Bob'); + */ +Collection.prototype.findAll = + util.deprecate(Collection.prototype.findAll, 'Collection#findAll: use Collection#filter instead'); + +Collection.prototype.filterArray = + util.deprecate(Collection.prototype.filterArray, 'Collection#filterArray: use Collection#filter instead'); + +Collection.prototype.exists = + util.deprecate(Collection.prototype.exists, 'Collection#exists: use Collection#some instead'); + +Collection.prototype.find = function find(propOrFn, value) { + if (typeof propOrFn === 'string') { + process.emitWarning('Collection#find: pass a function instead', 'DeprecationWarning'); + if (typeof value === 'undefined') throw new Error('Value must be specified.'); + for (const item of this.values()) { + if (item[propOrFn] === value) return item; + } + return null; + } else if (typeof propOrFn === 'function') { + for (const [key, val] of this) { + if (propOrFn(val, key, this)) return val; + } + return null; + } else { + throw new Error('First argument must be a property string or a function.'); + } +}; + +Collection.prototype.findKey = function findKey(propOrFn, value) { + if (typeof propOrFn === 'string') { + process.emitWarning('Collection#findKey: pass a function instead', 'DeprecationWarning'); + if (typeof value === 'undefined') throw new Error('Value must be specified.'); + for (const [key, val] of this) { + if (val[propOrFn] === value) return key; + } + return null; + } else if (typeof propOrFn === 'function') { + for (const [key, val] of this) { + if (propOrFn(val, key, this)) return key; + } + return null; + } else { + throw new Error('First argument must be a property string or a function.'); + } +}; + module.exports = Collection;