mirror of
https://github.com/danbulant/discord.js
synced 2026-06-10 02:02:40 +00:00
Implement missing Collection#reduce functionality
This commit is contained in:
parent
265ac90234
commit
28ca83011c
1 changed files with 20 additions and 6 deletions
|
|
@ -293,14 +293,28 @@ class Collection extends Map {
|
||||||
/**
|
/**
|
||||||
* Identical to
|
* Identical to
|
||||||
* [Array.reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce).
|
* [Array.reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce).
|
||||||
* @param {Function} fn Function used to reduce
|
* @param {Function} fn Function used to reduce, taking four arguments; `accumulator`, `currentValue`, `currentKey`,
|
||||||
* @param {*} [startVal] The starting value
|
* and `collection`
|
||||||
|
* @param {*} [initialValue] Starting value for the accumulator
|
||||||
* @returns {*}
|
* @returns {*}
|
||||||
*/
|
*/
|
||||||
reduce(fn, startVal) {
|
reduce(fn, initialValue) {
|
||||||
let currentVal = startVal;
|
let accumulator;
|
||||||
for (const [key, val] of this) currentVal = fn(currentVal, val, key, this);
|
if (typeof initialValue !== 'undefined') {
|
||||||
return currentVal;
|
accumulator = initialValue;
|
||||||
|
for (const [key, val] of this) accumulator = fn(accumulator, val, key, this);
|
||||||
|
} else {
|
||||||
|
let first = true;
|
||||||
|
for (const [key, val] of this) {
|
||||||
|
if (first) {
|
||||||
|
accumulator = val;
|
||||||
|
first = false;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
accumulator = fn(accumulator, val, key, this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return accumulator;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue