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

How to do dry concept in map function in JavaScript?

     // last 7 days data from db...

    let last7Days = result.map((data)=>data._id).slice(1).slice(-7)

    let last7daysIncome = result.map((data) =>  data.totalIncomeAmount).slice(1).slice(-7)

    let last7daysAvgIncome  = result.map((data)=> data.avrageIncome).slice(1).slice(-7)

    let last7daysPatientionsCount  = result.map((data)=> data.PatientionsCount).slice(1).slice(-7)

    let last7disease = result.map((data)=>data.diseaseArr).slice(1).slice(-7)

How to I simplify this code with DRY Concept in JavaScript?

And thanks.

code image

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

>Solution :

Create a function, send in the parameter for the field you want to extract, and even the number of days to look back:

function lastDays(result, field, days) {
  return result.map((data)=>data[field]).slice(1).slice(days);  
}
function lastSevenDays(result, field) {
  return lastDays(result, field, -7);
}

let last7Days = lastSevenDays(result, "_id")
let last7daysIncome = lastSevenDays(result, "totalIncomeAmount")
let last7daysAvgIncome  =lastSevenDays(result, "avrageIncome")
let last7daysPatientionsCount  = lastSevenDays(result, "PatientionsCount")
let last7disease = lastSevenDays(result, "diseaseArr")
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