Skip to content Skip to sidebar Skip to footer

Higher Order Functions Returning Anything But A Non-boolean Is Questionable. Why?

function each(collection, callback) { var arr = []; for(var i = 0; i < collection.length; i++) { var result = callback(collection[i]) if (typeof result !== 'unde

Solution 1:

If a function is called isNumber, it should return a boolean.

Also, your each function is a map not an each. In that case your code should probably look like.

functionflatMap(collection, callback) {
  var arr = [];
  for(var i = 0; i < collection.length; i++) {
      var result = callback(collection[i])
      if (typeof result !== 'undefined') {
        arr.push(callback(collection[i]));
      }
    }
  return arr;
}

functiontimes2(item) {
    if (typeof item === "number") {
      return item * 2;
    }
    return item;
}

map([1,2,3,"hello"], times2);

If you wanted iteration that can be stopped, then it would look like

functioniterate(collection, callback) {
  for(var i = 0; i < collection.length; i++) {
    var result = callback(collection[i])
    if (typeof result === false) {
      return;
    }
  }
}

functiondoSomethingAndStopIfNotANumber(item) {
   console.log(item);
   returntypeof item == "number";
}

iterate([1,2,3, "hello", 4, 5], doSomethingAndStopIfNotANumber);

Note that Array.prototype.forEach does not allow you to stop iteration by returning false, for that you'd need to misuse Array.prototype.every (because that function returns a boolean, so it's just a semantic problem, not like map where you build an array and throw it away) or write a function like I did above.

Post a Comment for "Higher Order Functions Returning Anything But A Non-boolean Is Questionable. Why?"