I’ve been learning some examples of form validation in Vue3 + TypeScript for a few days, and I see an implementation that I think is very clever.

Summary of demand

We have a list of functions called funcArr, such as funcArr = [func1, func2… . These functions are () => Boolean, which has no arguments and returns a Boolean value.

We expect every function in funcArr to be executed when the form is submitted, and our main logic gets true if all of these functions are validated, false otherwise.

Simple version

func1 = () = > { console.log(1); return true; }
func2 = () = > { console.log(2); return false; }
func3 = () = > { console.log(3); return true; }

funcArr = [func1, func2, func3];

result = true;
for (var i = 0; i < funcArr.length; i ++ )
{
  if(! funcArr[i]("i")) result = false;
}

console.log(result)
Copy the code

The output is:

> 1
> 2
> 3
> false
Copy the code

This is obviously a bit of nonsense, completely devoid of JavaScript features and functional programming.

Array.prototype.every()

In general, we use array.prototype.every () to solve these requirements.

According to MDN: every checks if every function passes and returns a Boolean.

So:

func1 = () = > { console.log(1); return true; }
func2 = () = > { console.log(2); return false; }
func3 = () = > { console.log(3); return true; }

funcArr = [func1, func2, func3];

result = funcArr.every(func= > func());

console.log(result)
Copy the code

Output:

> 1
> 2
> false
Copy the code

Notice that when every finds that one element fails validation, it stops checking other elements.

Combined with the map ()

Sometimes, functions in our funcArr do more than simply return a Boolean value, but there is other logic involved, such as modifying some reactive variable.

Therefore, we expect every to execute all functions, even if one of them is found to have returned false.

Consider using map.

func1 = () = > { console.log(1); return true; }
func2 = () = > { console.log(2); return false; }
func3 = () = > { console.log(3); return true; }

funcArr = [func1, func2, func3];

result = funcArr.map(func= > func()).every(res= > res);

console.log(result)
Copy the code

Output:

> 1
> 2
> 3
> false
Copy the code

Every acts as a funnel, filtering all values in order, returning false if one is false, and true otherwise.

I am small pat, welcome to pay attention to me, similar to this kind of clever skills of the pick-up will often update ha. Please click “like” and “watch”