Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to attach multiple class method from loop?

.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/)
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading