Iterate collection for truthy/falsey values

285 Views Asked by At

I have some outstanding requirements for a school assignment that should return truthy/falsy values from a collection. Here are the outstanding requirements:

1) Should pass for a collection of all truthy results

2) Should pass for a collection containing mixed truthy/falsy results

3) Should pass for a collection containing one string truthy value

4) Should pass for a collection containing one matching value

5) Should cast the result to a boolean

6) Should work when no callback is provided

I am really new to Javascript so I am not sure if all of the above can even be done in the same function, but that is how I read the assignment. Here is what I have so far:

  myCustomForEach = function(collection, iterator) {
      for(var val in collection){
          if (iterator(collection[val])) {
              return true;
          } else {
              return false;
          }
      }
  };

This is the function I need help with:

 myTruthTest = function(collection, iterator) {
     var result = _.every(collection, iterator);
     if (result) {
         return true;
     } else {
         return false;
     }
 };

I do not need to use the custom forEach, but I cannot use any built in functions. Am I over thinking this or am I right in thinking this will take more than 1 function to achieve the required results? Help much appreciated.

1

There are 1 best solutions below

2
On

You can use builtin filter function:

var myTruthTest = function(collection, iterator) {
    return !!collection.filter(function(item) {
        return !!item || iterator && iterator(item);
    }).length;
};