Imagine having an object like this:
const data = {
bills: 10,
rent: 40,
food: 50,
}
The total is 100 (or 100%).
If we update the bills
to a value of 20, the other properties should adjust accordingly, for example:
{
bills: 20,
rent: 30,
food: 50,
}
or
{
bills: 20,
rent: 35,
food: 45,
}
it varies.
A code snippet I created often causes one property to dip below zero because the sum becomes 102 instead of 100. Here's the problematic code: https://i.sstatic.net/RmVjb.png
The code snippet is as follows:
allocatePercentage(dataName, percentage) {
const curr = this.data[dataName];
this.data[dataName] = percentage;
if (percentage === 100) {
Object.keys(this.data).filter(key => key !== dataName).forEach(dataKey => {
this.data[dataKey] = 0;
});
} else {
const {[dataName]: current, ...rest} = this.data;
Object.keys(rest).forEach(key => {
this.data[key] = this.data[key] - ((percentage - curr) / Object.keys(rest).length);
});
}
}
Usage example:
allocatePercentage('bills', 20);
Assuming the object looks like this:
{
bills: 10,
rent: 40,
food: 50,
}
for rent:
data['rent'] = 40 - ((20 - 10) / 2) // 35
for food:
data['food'] = 50 - ((20 - 10) / 2) // 45
Why does it sometimes result in a negative % value? (as shown in the photo)
How can I avoid this and accurately distribute the percentage?