Home > front end >  How to write a Generalized function to perform OR operation in TypeScript?
How to write a Generalized function to perform OR operation in TypeScript?

Time:11-17

In TypeScript, is there a way we can create a generalized function to execute OR operation for any number of arguments passed?

I can write a function for 2 arguments. The requirement is to generalize this for any number of arguments.

export const performOR = (arg1, arg2) => arg1 || arg2;

const isArg1OrArg2 = performOR(x, y);

If this can be achieved by passing an array of arguments, that's also fine.

CodePudding user response:

This sounds like homework, but:

export const performOR = (...args: any[]):boolean  => {
  for(const item of args) {
    if (item) return true;
  }
  return false;
}

CodePudding user response:

With the help of the above-posted answer, I have generalized both OR and AND operations with a bit of modifications. Might be helpful for any other person looking for a similar solution.

const performOR = (...args: any[]):boolean  => {  
  return args.some(arg => arg === true);
}

const performAND = (...args: any[]):boolean  => {  
  return args.every(arg => arg === true);
}

performOR(true, false);
performAND(true, true);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related