I have an array of strings, amount and a percentage.
Every key is found in the object.
Its value is equal to the previous value plus the percentage.
This is the code I wrote:
const keys = ['a', 'b', 'c'];
const amount = 300;
const precentage = 0.5;
const obj = {};
let prevAmount = amount;
for (let i = 0; i < keys.length; i++) {
if (i !== 0) {
obj[keys[i]] = prevAmount + prevAmount * precentage;
prevAmount = prevAmount + prevAmount * precentage;
} else {
obj[keys[i]] = amount;
prevAmount = amount;
}
}
The obj is:
{a: 300, b: 450, c: 675}
I don’t like this code. It looks too long for me.
Is there a way to make it more readable and short?
>Solution :
You can simply track the previous amount and update it on each iteration.
const keys = ['a', 'b', 'c'];
const amount = 300;
const percentage = 0.5;
const result = {};
let prev = amount;
for (const key of keys) {
result[key] = prev;
prev = prev + (prev * percentage);
}
console.log(result)