Home > Net >  How to attach multiple class method from loop?
How to attach multiple class method from loop?

Time:03-23

.regularExpression() is hardcoded 3 times in the script, is there a way to dynamically attach it from loops from variable const regex = ['reg1', 'reg2', 'reg3']?

Usage:

{
       text: Check.string()
                  .regularExpression(/reg1/)
                  .regularExpression(/reg2/)
                  .regularExpression(/reg3/)
}

CodePudding user response:

You can use the reduce method:

const regex = ['reg1', 'reg2', 'reg3'];
{
  text: regex.reduce((check, regex) => check.regularExpression(new RegExp(regex)), Check.string())
}

In this way, starting from the initial value Check.string(), you will iteratively chain new regular expressions, accordingly to your array.

Alternatively, you can use a plain for-loop:

let check = Check.string();
for (const item of regex) {
  check = check.regularExpression(new RegExp(regex));
}

{
  text: check
}
  • Related