I have these 2 functions, if I seperate them I would have a lot of redundant codes. You can see what it does here https://jsfiddle.net/8m9zbefq/ basically I just want to transform the data structure.
How can I refactor two function into 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 this thought, use template literal to make the 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 the approach fine?