mirror of
https://github.com/danbulant/discord.js
synced 2026-06-08 09:13:22 +00:00
Add Collection.find with function
This commit is contained in:
parent
774b4d4694
commit
ac1f5f32e2
2 changed files with 22 additions and 10 deletions
File diff suppressed because one or more lines are too long
|
|
@ -77,20 +77,32 @@ class Collection extends Map {
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns a single item where `item[key] === value`
|
* Returns a single item where `item[key] === value`, or the given function returns `true`. In the latter case,
|
||||||
* @param {string} key The key to filter by
|
* this is identical to
|
||||||
* @param {*} value The expected value
|
* [Array.find()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find).
|
||||||
|
* @param {string|function} keyOrFn The key to filter by, or the function to test with
|
||||||
|
* @param {*} [value] The expected value - required if using a key for the first param
|
||||||
* @returns {*}
|
* @returns {*}
|
||||||
* @example
|
* @example
|
||||||
* collection.find('id', '123123...');
|
* collection.find('id', '123123...');
|
||||||
|
* @example
|
||||||
|
* collection.find(val => val.id === '123123...');
|
||||||
*/
|
*/
|
||||||
find(key, value) {
|
find(keyOrFn, value) {
|
||||||
if (typeof key !== 'string') throw new TypeError('Key must be a string.');
|
if (typeof keyOrFn === 'string') {
|
||||||
if (typeof value === 'undefined') throw new Error('Value must be specified.');
|
if (typeof value === 'undefined') throw new Error('Value must be specified.');
|
||||||
for (const item of this.values()) {
|
for (const item of this.values()) {
|
||||||
if (item[key] === value) return item;
|
if (item[keyOrFn] === value) return item;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
} else if (typeof keyOrFn === 'function') {
|
||||||
|
for (const [key, val] of this) {
|
||||||
|
if (keyOrFn(val, key, this)) return val;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
} else {
|
||||||
|
throw new Error('First parameter must be a string key or a function.');
|
||||||
}
|
}
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue