What this functionality does is that for each priority it will rebalance the percentage (Participacion) in equal parts. The problem occurs in odd cases, for example when there are 3 priorities(Prioridad), you must divide 100 / 3, which gives a result of 33 (and 33 33 33 = 99 )
What should I add to my code, so that when the result of the division is not 100, the missing numbers are added to the last position, completing the 100.
Example problem 1 : Example gif : The idea is that the last 33 that you see in the gif is automatically transformed into a 34.Tthis is the code i have so far:
rebalance(){
this.beneficiarios = this.beneficiarios.sort((a, b) =>Number(a.Prioridad) - Number(b.Prioridad)).map((val, i, beneficiarios) => {
const priorityLenght = this.beneficiarios.filter((a) =>
Number(a.Prioridad) == Number(val.Prioridad)).map((b) =>
Number(b.Participacion)).length
const arrObj = {
...val,
Participacion : 100 / priorityLenght
}
return arrObj;
})
}
Problem 2: In the previous gif you can see that when you press the button, the rebalancing was done for all the priorities (Prioridad), I would like it to be only for those that contain a 0 in percentage (Participacion)
I'm pretty sure that both problems can be solved by adding a couple lines of code to the function I put above, but I lack experience to know what to do
Here a StackBlizz of the proyect: https://stackblitz.com/edit/create-a-basic-angular-component-v8k1hs?file=src/app/example/user.component.ts
CodePudding user response:
I fixed your algorithm. Really just needed a slightly different approach. I changed it to use Math.floor() for participation and then got the diff (100 % length) needed to make the value 100% and added that to the last value. Here is the updated stackblitz.
PS: never make method calls in the template due to the overhead the this add each time change detection runs; instead use pure pipes or calculate their value for presentation when the data changes. There was a decimal formatting method being called that I removed.