collection-every2

by shan10213223

JavaScript

var _ = {};

// _.every(collection, [predicate], [context])
// Returns true if all values in the collection pass the predicate truth test.
// Predicate is called with three arguments:
// (element, index|key, collection), and bound to the context if one is passed.
// Short-circuits and stops traversing the list if a false element is found.
// TIP: without the short-circuiting you could reuse _.reduce(). Can you figure how?
// Because of the short-circuiting though, you need to re-implement a modified _.each().
_.every = function (collection, predicate, context) {
  if (context) {
    predicate = predicate.bind(context);
  }
  if (Array.isArray(collection)) {
    for (let i=0; i<collection.length; i++) {
      if (Object.prototype.hasOwnProperty.call(collection, i)) {
        if (collection[i] == null) {
          return false;
        } else if (predicate(collection[i], i, collection) === false) {
          return false;
        }
      }
    }
  } else {
    for (let key in collection) {
      if (Object.prototype.hasOwnProperty.call(collection, key)) {
        if (collection[key] == null) {
          return false;
        } else if (predicate(collection[key], key, collection) === false) {
          return false;
        }
      }
    }
  }
  return true;
};


// tests
/*let simple_array = [1,2,3,-2];
let simple_array2 = [1,2,3];
let simple_obj1 = {a:1, b:2, c:3};
let simple_obj2 = {a:1, b:2, c:3, d:-2};

console.log(_.every(simple_array, function(val) {
  return val>0;
}));

console.log(_.every(simple_array2, function(val) {
  return val>0;
}));

console.log(_.every(simple_obj1, function(val, key) {
  return val>0;
}));

console.log(_.every(simple_obj2, function(val, key) {
  return val>0;
}));*/


/*let test1 = _.every([2, 4, 5], function(num) { return num % 2 == 0; });
console.log(test1);
//=> false

let test2 = _.every([2, 4, 6], function(num) { return num % 2 == 0; });
console.log(test2);*/

/*
let half_true_array1 = [false, true, 'yes', null,...