0

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.

jcubic
  • 61,973
  • 54
  • 229
  • 402

1 Answers1

0

You can use builtin filter function:

var myTruthTest = function(collection, iterator) {
    return !!collection.filter(function(item) {
        return !!item || iterator && iterator(item);
    }).length;
};
jcubic
  • 61,973
  • 54
  • 229
  • 402
  • It needs to return a boolean value (i think). So I was thinking `_.some` might be better. – Paul Nikonowicz May 22 '15 at 16:39
  • Some would be ideal, which is basically what I am trying to build myself, but this is the sticking point. I am trying to do _.some, without using _.some, if that makes sense, as I cannot use any built in functions. This exercise is to learn how these functions work. –  May 22 '15 at 16:43