Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Array by percentage of the previous value

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading