samedi 18 septembre 2021

Checking lots of variables for truthiness in a single pass

I have a large form with many fields and a special processing function
Several variables of different types declared at the beginning of a function

I would like to check that a user has set all variables before a function execution

const a1 = true, a2 = "str", a3 = { b: true }, a4 = [], a5 = "";

// Variant 1: old school
if (!(a1 && a2 && a3 && a4 && a5))
  return toast.error('Please fill out all fields');

// Variant 2: array aggregation
if (!Array.of(a1, a2, a3, a4, a5).every(Boolean))
  return toast.error('Please fill out all fields');

I would like to catch a5, since it's an empty string

Variant 1 is not readable if we have 5+ variables and not very elegant
Variant 2 is more elegant and clear but doesn't work for variables of not type Boolean

How do you check lots of variables in one pass?

Aucun commentaire:

Enregistrer un commentaire