WonBok Lee
WonBok Lee

Reputation: 33

implement underscore _.every()

I have a question about implementing _.every().

My code is here

  _.every = function(collection, iterator) {

    if (collection.length === 0) {
      return true;
    }
    return _.reduce(collection, function(accum, item){
      if(!iterator(item)){
        return false;
      } else if((iterator(item))){
        return accum;
      }

    },true);

  };

However, accorting to the Underbar Test Suite, my code doesn't work with the statement "should work when no callback is provided"

expect(_.every([true, true, true])).to.be.true;

   expect(_.every([true, true, false])).to.be.false;

expect(_.every([false, false, false])).to.be.false;

I don't know what's wrong with my code.

Please, let me know hot to correct it.

Upvotes: 0

Views: 660

Answers (1)

nrg
nrg

Reputation: 518

See what happens if you do not pass the iterator callback.

_.every = function(collection, iterator) { // <-- iterator is undefined
  if (collection.length === 0) {
    return true;
  }

  return _.reduce(collection, function(accum, item){
    if(!iterator(item)){           // <-- undefined is not a function! This will throw an error!
      return false;
    } else if((iterator(item))){
      return accum;
    }
  },true);
};

In order to fix this, you'd need to check if iterator is defined and then call it. Otherwise do some other tests based on your collection items.

Alternatively, you can provide the default value for iterator. This solution might be simpler:

_.every = function(collection, iterator) { // <-- iterator is undefined
  if (collection.length === 0) {
    return true;
  }

  // overwrite iterator if it's falsy (in your case it's undefined)
  iterator = iterator || function(item) {
    return item;
  };

  return _.reduce(collection, function(accum, item){
    if(!iterator(item)){
      return false;
    } else if((iterator(item))){
      return accum;
    }
  },true);
};

Upvotes: 1

Related Questions