Skip to content
Advertisement

Who can explain the reason of the behavior of this code

function every(array, predicat) {
  let val;
  for (let elt of array) {
    val = predicat(elt);
  }
  if (val == true) console.log(true);
  else console.log(false);
}
every([1, 2, 3, 4, 5], n => n > 0)

what i want it to do is to pass all the values in the predicat() and return true if all is true and false if at least one value return false

Advertisement

Answer

Edit

If you want to log every time, you could try adding another control variable. You would need the current result and the final result. This would not short-circuit and it would check every value within the array. I would not recommend doing this, so consider what I originally responded with below.

function every(array, predicat) {
  let finalVal = true, currentVal;
  for (let elt of array) {
    currentVal = predicat(elt);
    console.log(elt, currentVal);
    if (finalVal && !currentVal) {
      finalVal = false;
    }
  }
  return finalVal;
}

every([1, 2, 3, 4, 5], n => n > 0)

Original response

You should be short-circuiting if the predicate fails at any point since you are checking every. There is no point to storing the result, you should just return.

function every(array, predicat) {
  for (let elt of array) {
    if (!predicat(elt)) {
      return false; // short-circuit
    }
  }
  return true;
}

console.log(every([1, 2, 3, 4, 5], n => n > 0));

Here is a version of some, that checks for a truth and then breaks out. You just flip the condition and the return values.

function some(array, predicat) {
  for (let elt of array) {
    if (predicat(elt)) {
      return true; // short-circuit
    }
  }
  return false;
}

console.log(some([1, 2, 3, 4, 5], n => n > 0));
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement