Negative days in the invoice

I have a website where people can sell products. Every time they add a product, they have to pay me 10 cents. Each user has something that can be compared to a bank account. Therefore, when they add a product, their account is -10 cents. Each user can only have a negative account for x days.

So, I need an algorithm that can calculate how many days the user has had a negative.

The data looks like this:

var data = [
  { amount: -10, ago: 15 },
  { amount: 10,  ago: 10 },
  { amount: -10, ago: 5 }
];

So, this account has been negative for 5 days. (In my application, I use dates, but to keep things simple, I use the "days ago" here.)

Another example:

var data = [
  { amount: -10, ago: 15 },
  { amount: -10, ago: 10 },
  { amount: -10, ago: 5 }
];

This account has been negative for 15 days.

, , , ?

: http://jsfiddle.net/SK2By/1/

: http://jsfiddle.net/SK2By/

+3
1

:

var negativeDays = function (data) {

    var i, balance = 0, daysNegative = 0;

    for (i = 0; i < data.length; i++) {
        balance += data[i].amount;

        if (balance < 0) {
            if (daysNegative === 0) {
                daysNegative = data[i].ago;
            }
        } else {
            daysNegative = 0;
        }
    }

    return daysNegative;
};

jsFiddle: http://jsfiddle.net/willslab/SK2By/7/

+2

All Articles