collections-invoke1

by shan10213223

JavaScript

var _ = {};
_.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));
      }
    }
  } 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));
      }
    }
  }
  return results;
};
// _.invoke(collection, methodName, *arguments)
// Returns an array with the results of calling the method
// indicated by methodName on each value in the collection.
// Any extra arguments passed to invoke will be forwarded on to the method invocation.
_.invoke = function (collection, methodName) {
  console.log(Array.prototype.slice.call(arguments, 2));
  //console.log(methodName, typeof(methodName));
  let args = Array.prototype.slice.call(arguments, 2);
  console.log('arguments: ' + arguments);
  console.log(arguments);
  console.log('methodName: ' + methodName);
  console.log('args: ' + args);
  let results = [];
  return _.map(collection, function (item, key) {
    return item[methodName].apply(item, args);
    //return item[methodName];
  });
};

// ref
// https://stackoverflow.com/questions/9854995/javascript-dynamically-invoke-object-method-from-string

/*let array1 = [[5, 1, 7], [3, 2, 1]];
console.log(sort.apply(array1));
console.log(array1);*/
/*let string1 = 'ABC';
console.log(string1.toLowerCase());
console.log(toLowerCase.apply(string1));*/
// ref
// https://stackoverflow.com/questions/28319891/what-is-the-different-methods-available-in-invoke-using-underscorejs

// tests

let test1 = _.invoke([[5, 1, 7], [3, 2, 1]], 'sort', [1,2,3],...