Home > Mobile >  Using Array.prototype.every or Array.property.some depending on condition
Using Array.prototype.every or Array.property.some depending on condition

Time:05-13

I'm trying to make a function to filter some data using OR/AND logical operator depending on what the user selects. That means I need to use Array.prototype.every (AND) or Array.property,some (OR) to fullfill my requirement.

To avoid code redundancy I was trying to do something like this:

const functionApplied = condition === 'ALL'
        ? myArray.every
        : myArray.some;

functionApplied(item =>  {
    ... aux code ...
})
functionApplied.call(item =>  {
    ... aux code ...
})

Is there an analogous way to do it like this?

I know I could do something like this, but I'm just curious about above sintax...

const auxFunction = (item) => {...};
if (condition === 'ALL') {
    myArray.every(item => auxFunction(item));
} else {
    myArray.some(item => auxFunction(item));
}

CodePudding user response:

You can definitely do something similar to what you're hoping to achieve. Here's one way:

function checkCondition(condition, booleanFunc, myArray) {
    const functionApplied = condition === 'ALL'
        ? myArray.every.bind(myArray)
        : myArray.some.bind(myArray);

    return functionApplied(booleanFunc);
}

console.log(checkCondition('ANY', (item) => {return item > 2}, [1,4,5,6]));
console.log(checkCondition('ANY', (item) => {return item > 2}, [4,5,6]));
console.log(checkCondition('ANY', (item) => {return item > 2}, [1,2]));
console.log(checkCondition('ALL', (item) => {return item > 2}, [1,4,5,6]));
console.log(checkCondition('ALL', (item) => {return item > 2}, [4,5,6]));

VLAZ comment is another good direction.

CodePudding user response:

Yep, VLAZ comment is the way I wanted, this works:

const functionApplied = condition === 'ALL'
        ? Array.prototype.every
        : Array.prototype.some;

functionApplied.call(myArray, item =>  {
    ... aux code 

Thanks everyone for your quick answers :)

CodePudding user response:

const result = (myArray[condition === 'ALL' ? 'every': 'some'])(item => auxFunction(item))

CodePudding user response:

I would personally use the following:

const fn = condition === 'ALL' ? "every" : "some";
const result = myArray[fn]((item) => {
  // ... aux code ...
});

Storing the function name every or some in a variable called fn. Then calling it supplying your aux code.

CodePudding user response:

You can use a variable holding the property name, and then use dynamic property access.

function functionApplied(condition) {
  return functionApplied === 'ALL' ? 'every' : 'some';
}

let result = myArray[functionApplied(condition)](item => { ... });

  • Related