ServerSideSkittles
ServerSideSkittles

Reputation: 2973

Javascript decrement from 10 then do something when 0

I have a function that when called will decrease by 1. It is called when a user reports something. I want to be able to store this and then when it hits 0, to execute an action.

function userReported() {

    console.log('user report ' + add());

    var add = (function () {
          var counter = 10;
          return function () {
            counter -= 1; 
            return counter;

          }

    })();

}

Now the problem is I can return the counter so it logs down from 10. But the issue I have is that I can seem to add an if/else before returning counter as it does not store the variable.

I attempted the following but it doesn't work and I don't know how to return something > store it, and at the same time check its value. I also tried a while loop but failed too.

function userReported() {

    var limit = add;

    if ( limit <= 0 ) {
        console.log('Link does not work!'); 
        }
        else {
            console.log('user report ' + limit);
        }

    var add = (function () {
          var counter = 10;
          return function () {
            counter -= 1; 
            return counter;

          }

    })();


}

How do I go about creating a value, increment/decrement said value, then when it reaches a number -> do something?

Upvotes: 0

Views: 1530

Answers (2)

Arthur Serafim
Arthur Serafim

Reputation: 423

Ok, if you need to get a report based on an external limit, you could do something like that:

var limit = 10;

function remove() {
  limit -= 1;
}

function userReport() {
  if (limit <= 0) {
    console.log("Link does not work!");
  } else {
    remove();
    console.log(`User report: ${limit}`);
  }
}

userReport();

If that's what you want, removing the remove function from userReport and taking the limit variable out will make things work

Upvotes: 1

Mark
Mark

Reputation: 92440

You would typically do this with a function that returns a function that captures the counter in a closure. This allows the returned function to maintain state over several calls.

For example:

function createUserReport(limit, cb) {

    console.log('user report initiated' );

    return function () {
        if (limit > 0) {
            console.log("Report filed, current count: ", limit)
            limit--
        } else if (limit == 0) {
            limit--
            cb() // call callback when done
        } 
        // do something below zero?
    }
}

// createUserReport takes a limit and a function to call when finished
// and returns a counter function
let report = createUserReport(10, () => console.log("Reached limit, running done callback"))

// each call to report decrements the limit:
for (let i = 0; i <= 10; i++){
    report()
}

You can of course hard-code the callback functionality and limit number into the function itself rather than passing in arguments.

Upvotes: 2

Related Questions