John Doe
John Doe

Reputation: 25

Execute only when array's length reaches X elements

I was wondering if it's possible to execute function only when arrays length is long enough.

I have a setInterval function to repeatedly fetch info from interweb, if a new user appears it will send his id to an array, and I want to execute different function only when this array's length reaches a specific amount.

Thanks in advance!

Upvotes: 2

Views: 1054

Answers (3)

Alberto Trindade Tavares
Alberto Trindade Tavares

Reputation: 10396

You can use a Proxy for the array to observe the changes on it. In set, you can check the length of the array and trigger an action:

var lengthToTriggerFunction = 3;
var functionToBeTriggered = function() {
  console.log('Triggered!');
}

var changeHandler = {
  set: function(target, property, value, receiver) {
    target[property] = value;
    
    if (property === 'length' && target.length === lengthToTriggerFunction) {
       functionToBeTriggered();
    }

    return true;
  }
};

var array = new Proxy([], changeHandler);

array.push(1);
console.log(array.length);

array.push(2);
console.log(array.length);

array.push(3); // function is triggered here
console.log(array.length);

array.push(4);
console.log(array.length);

Upvotes: 2

Sean Horning
Sean Horning

Reputation: 41

Not sure if this is as simple as it sounds, but why not just check the array length after each insertion of a new user into said array. If length is greater than your desired size, simply call the function.

Upvotes: 2

Reticulated Spline
Reticulated Spline

Reputation: 821

After each item is added you can check the length property of the array:

addUser(...) {
  array.push(...)
  if (array.length > x) {
   execute();
 }
}

Upvotes: 4

Related Questions