collections-map2

by shan10213223

JavaScript

var _ = {};
// _.map(collection, iteratee, [context])
// Returns a new array of values by mapping each value in collection through iteratee.
// Each invocation of iteratee is called with three arguments:
// (element, index|key, collection), and bound to the context if one is passed.
_.map = function (collection, iteratee, context) {
  let results = [];
  if (context) {
    iteratee = iteratee.bind(context);
  }
  if (Array.isArray(collection)) {
    for (let i=0; i<collection.length; i++) {
      if (Object.prototype.hasOwnProperty.call(collection, i) &&
     Object.prototype.propertyIsEnumerable.call(collection, i)) {
       results.push(iteratee(collection[i], i, collection));
     }
     // results.push(iteratee(collection[i], i, collection));
    }
  } else {
    for (let key in collection) {
      if (Object.prototype.hasOwnProperty.call(collection, key) &&
     Object.prototype.propertyIsEnumerable.call(collection, key)) {
       results.push(iteratee(collection[key], key, collection));
     }
     // results.push(iteratee(collection[key], key, collection));
    }
  }
  return results;
};

// ref
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind


// tests
test1 = _.map([1, 2, 3], function(num){ return num * 3; });
console.log(test1);
//=> [3, 6, 9]

test2 = _.map({one: 1, two: 2, three: 3}, function(num, key){ return num * 3; });
console.log(test2);