-1

Can a predicate be an object in JavaScript (as in C++)?

For example, is it possible to find the index of an element in an array (with arr.findIndex(pred)) with a predicate like this?

    class Predicate
    {
        constructor()
        {
            this.sum = 0;
        }

        evaluate(elem)
        {
            this.sum += elem;
            return sum > 25;
        }
    }

    const pred = new Predicate();

    const index = arr.findIndex(pred);

EDIT1: If no, what is the easiest way to find the index of an element that makes the sum of it and all the previous elements exceed 25?

Alexey Starinsky
  • 3,699
  • 3
  • 21
  • 57

3 Answers3

1

It should be a callback, this the function definition

arr.findIndex(callback(element[, index[, array]])[, thisArg])

You can provide your Predicate objects evaluate method. Like this

const index = arr.findIndex(pred.evaluate,pred);// pass pred as thisArg
Abhi
  • 398
  • 1
  • 11
  • 1
    You need to either bind the method or pass the instance as a `thisArg` – Yury Tarabanko Nov 15 '18 at 13:19
  • findIndex is being called on arr (Array), method is bound to the array. It runs perfectly fine. – Abhi Nov 15 '18 at 13:31
  • my bad, i removed his logic and just tested the callback. Edited answer.Thank you for pointing out! http://jsfiddle.net/4ga3sLy9/3/ – Abhi Nov 15 '18 at 13:59
1

Predicate has to be a function. MDN. But you could always create a function that returns another function.

const runningSum = (sum, current = 0) => value => (current += value) > sum

const index = [1, 2, 3, 4, 5, 6, 7, 8, 9].findIndex(runningSum(25))

console.log(index)
Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98
1

There is no such thing as an evaluate method (that would get invoked when an object gets called like a function) in JavaScript. However, functions themselves are objects and you could even create them with class syntax. It's not very useful though, in JS you would just write a closure to create a function with instance-specific values:

function predicate(max) {
    var sum = 0;
    return function(elem) {
        sum += elem;
        return sum > max;
    };
}

const pred = predicate(25);

const index = arr.findIndex(pred);
Bergi
  • 630,263
  • 148
  • 957
  • 1,375