From 28ca83011c5775ce0f1c643a261b4138b42a416d Mon Sep 17 00:00:00 2001 From: Schuyler Cebulskie Date: Sat, 24 Dec 2016 01:59:01 -0500 Subject: [PATCH] Implement missing Collection#reduce functionality --- src/util/Collection.js | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/src/util/Collection.js b/src/util/Collection.js index f90079bae..bafe710b6 100644 --- a/src/util/Collection.js +++ b/src/util/Collection.js @@ -293,14 +293,28 @@ class Collection extends Map { /** * Identical to * [Array.reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce). - * @param {Function} fn Function used to reduce - * @param {*} [startVal] The starting value + * @param {Function} fn Function used to reduce, taking four arguments; `accumulator`, `currentValue`, `currentKey`, + * and `collection` + * @param {*} [initialValue] Starting value for the accumulator * @returns {*} */ - reduce(fn, startVal) { - let currentVal = startVal; - for (const [key, val] of this) currentVal = fn(currentVal, val, key, this); - return currentVal; + reduce(fn, initialValue) { + let accumulator; + if (typeof initialValue !== 'undefined') { + 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; } /**