Ishara M
Ishara M

Reputation: 287

How to write a Generalized function to perform OR operation in TypeScript?

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.

Upvotes: 0

Views: 118

Answers (2)

Ishara M
Ishara M

Reputation: 287

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);

Upvotes: 0

Evert
Evert

Reputation: 99533

This sounds like homework, but:

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

Upvotes: 1

Related Questions