Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negative days in account

I have a website where people can sell products. Each time they add a product they have to pay me 10 cent. Every user has something which you can compare to a bank account. So when they add a product their account goes -10 cent. Each user can only have a negative account for x amount of days.

So I need an algorithm that can calculate how many days an account has been negative.

The data looks like:

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 app I am using dates but to keep things simple I am using "days ago" here. )

An other example:

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

This account has been negative for 15 days.

I already solved the problem myself but maybe there is a more elegant solution?

My solution to this problem: http://jsfiddle.net/SK2By/1/

Empty template to test your algorithm: http://jsfiddle.net/SK2By/

like image 692
Pickels Avatar asked Nov 23 '25 14:11

Pickels


1 Answers

Here is another approach to consider:

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/

like image 84
Will Klein Avatar answered Nov 25 '25 03:11

Will Klein



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!