javascript - refactor functions using template literal -


i have these 2 functions, if seperate them have lot of redundant codes. can see here https://jsfiddle.net/8m9zbefq/ want transform data structure.

how can refactor 2 function one?

const prepare_femaleobj = raw.map((obj, i) => {   const female_count = obj.age_data.reduce((accum, obj2) => {     if(obj2.female_count) return accum + obj2.female_count   }, 0)    const percentage = female_count / total_female_count * 100    return { id: ++i, camera: obj.device_info.name + ' - ' + obj.device_info.entrance_name, percentage } })  const prepare_maleobj = raw.map((obj, i) => {   const male_count = obj.age_data.reduce((accum, obj2) => {     if(obj2.male_count) return accum + obj2.male_count   }, 0)    const percentage = male_count / total_male_count * 100    return { id: ++i, camera: obj.device_info.name + ' - ' + obj.device_info.entrance_name, percentage } }) 

i've thought, use template literal make gender dynamic

const prepare_obj = (gender) => raw.map((obj, i) => {   const `${gender}_count` = obj.age_data.reduce((accum, obj2) => {     if(obj2[`${gender}_count`)] return accum + obj2.female_count   }, 0)    ... }) 

is approach fine?


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -