collections-reduce2

by shan10213223

JavaScript

var _ = {};
// _.reduce(collection, iteratee, [accumulator], [context])
// Reduce boils down a collection of values into a single value.
// Accumulator is the initial state of the reduction,
// and each successive step of it should be returned by iteratee.
// Iteratee is passed four arguments: (accumulator, element, index|key, collection),
// and bound to the context if one is passed. If no accumulator is passed
// to the initial invocation of reduce, iteratee is not invoked on the first element,
// and the first element is instead passed as accumulator for the next invocation.
_.reduce = function (collection, iteratee, accumulator, context) {
  if (context) {
      iteratee = iteratee.bind(context);
    }
  // if array
  if (Array.isArray(collection)) {
    if (isNaN(accumulator)) {
      let total = collection[0];
      for (let i=1; i<collection.length; i++) {
        total = iteratee(total, collection[i], i, collection);
      }
      return total;
    } else {
      let total = accumulator;
      for (let i=0; i<collection.length; i++) {
        total = iteratee(total, collection[i], i, collection);
      }
      return total;
    }
  // if object
  } else {
    if (isNaN(accumulator)) {
      let total = 0
      for (let key in collection) {
        total = iteratee(total, collection[key], key, collection)
      }
      return total;
    } else {
      let total = accumulator;
      for (let key in collection) {
        total = iteratee(total, collection[key], key, collection)
      }
      return total;
    }
  }
};

// test 1
var sum1 = _.reduce([1, 2, 3], function(memo, num){ return memo + num; }, 0);
console.log(sum1);
//=> 6
var sum2 = _.reduce([4, 5, 6], function(memo, num){ return memo + num; });
console.log(sum2);
//=> 6

// test 2
var pilots = [
  {
    id: 10,
    name: "Poe Dameron",
    years: 14,
  },
  {
    id: 2,
    name: "Temmin 'Snap' Wexley",
    years: 30,
  },
  {
    id: 41,
    name: "Tallissan Lintra",
    years: 16,
  },
  {
   ...