1

I need to check that there are at least 2 values before running a script, but can't seem to get the condition to fire.

When I use if (risForm) {... the script runs when risForm is filled, and when I use if (!(risForm)) {... the script runs if risForm is empty, but I can't seem to work out how to check if any 2 of the three is full... I've tried this:

if ((!(risForm)) + (!(runForm)) + (!(angForm)) < 2) {...

along with a numerous adjustments to precise formatting/bracketting, but it's not getting me anywhere!

5 Answers 5

4

Make an array of the variables, filter by Boolean, then check the length of the array:

const forms = [risForm, runForm, angForm];
if (forms.filter(Boolean).length < 2) {
  throw new Error('Not enough forms are filled');
}
// rest of the code

You can avoid creating an intermediate array by using reduce instead, if you wanted:

const filledFormCount = forms.reduce((a, form) => a + Boolean(form), 0);
if (filledFormCount < 2) {
  throw new Error('Not enough forms are filled');
}
1
  • Sure, you can do it inline, I just didn't want to cram too much inside the parentheses of an if because it makes the code less readable Jan 16, 2020 at 2:36
2

If you can have all your variables inside an array, you can do

yourArray.filter(Boolean).length >= 2

To break it apart, let's rewrite the above in a more verbose fashion:

yourArray
    .filter(
        function (variable) {
            return Boolean(variable)
        }
    )
    .length >= 2

Now, array.filter() gets every variable in the array and runs each as the argument for the function inside the parens, in this case: Boolean(). If the return value is truthy, the variable is "filtered in", if not it is "filtered out". It then returns a new array without the variables that were filtered out.

Boolean() is a function that will coerce your value into either true or false. If there's a value in the variable, it will return true... But there's a catch: it will return false for zeroes and empty strings - beware of that.

Finally, we use .length to count how many variables were "filtered in" and, if it's more than two, you can proceed with the code.

Maybe this pseudo code can illustrate it better:

const variables = ['foo', undefined, 'bar'];

variables.filter(Boolean).length >= 2;

['foo', undefined, 'bar'].filter(Boolean).length >= 2;
keepIfTruthy(['foo' is truthy, undefined is falsy, 'bar' is truthy]).length >= 2;
['foo', 'bar'].length >= 2;
2 >= 2;
true;
1
  • Answers seemed to fall into either "as close to original attempt as possible" (which seemed to err on the side of more new concepts and code shortcuts like => and !!) and "here's what you described" (using an array). As the array option seemed the best fit for what I was saying I wanted to do to me, plus the easiest to understand, and this one was the absolute clearest... Thanks for taking the time to break it down! Jan 16, 2020 at 3:49
1

Javascript's true and false are useful here because when coerced to a number, they become respectively 1 and 0. So...

function foo(a,b,c) {
  const has2of3 = !!a + !!b + !!c;

  if ( has2of3 ) {
    // Do something useful here
  }

}

One caveat, though is that the empty string '' and 0 are falsy, which means they would be treated as not present. If that is an issue, you could do something like this:

function foo(a,b,c) {
  const hasValue = x => x !== undefined && x !== null;
  const has2of3  = hasValue(a) + hasValue(b) + hasValue(c);

  if ( has2of3 ) {
    // Do something useful here
  }

}
1
  • 1
    I didn't end up using any of the answers provided because there was a hidden advantage in my specific instance that I'd neglected to consider, but trying to apply the "!!" boolean coercion trick is what made me see it! Thanks for that, wasn't aware of it before and it's gonna come way in handy! Jan 16, 2020 at 3:50
1

There many ways to solve this. Lets try with basic idea. You want to make a reusable code and something that support multiple variables, also condition value might change. This means, we need to define an array of the form values and a condition value to verify. Then we can apply a function to verify the condition. So let's try some code:

let risForm, runForm, angForm;
risForm = 'Active';
// runForm = 3;

const formValues = [risForm, runForm, angForm];
const minFilledForms = 2;

const hasValue = a => !!a && a !== undefined && a !== null;

verifyForms();

function verifyForms() {
  let filledForms = formValues.reduce((count, form) => count + hasValue(form), 0);
  if (filledForms < minFilledForms) {
    console.log(`Only ${filledForms} of ${formValues.length} forms have filled. Minimum ${minFilledForms} forms are requiered.`);
  }

  console.log('Continue...');
}

1
  • hi there! could you please email info @ panabee dot com about a potential job opportunity? please indicate when you see this message so i can delete it. thanks!
    – Crashalot
    Apr 12, 2020 at 2:20
0

let risForm = "a",
runForm = "",
angForm = "";

let arr = [risForm, runForm, angForm]

let res = arr.filter(el => !el || el.trim() === "").length <= 1

console.log(res)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.