1

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?

Cecilia Chan
  • 679
  • 2
  • 8
  • 17
  • I think you forgot the `female` on `return accum + obj2.female_count` – Arthur Aug 21 '17 at 08:24
  • @Arthur where is it? My code is working fine right? just that I don;t know how to refactor 2 function into 1 – Cecilia Chan Aug 21 '17 at 08:32
  • yes, yes removed all instance of `male` and `female` to handle a `gender` varaible. But on line3 you increment the `gender_counte` with `female_counter` instead of the good one (base on `gender` var). On your new function, the both call (for male and female) will return female results – Arthur Aug 21 '17 at 08:36
  • Also `if(obj2[\`${gender}_count\`)]` have syntaxe error > `( [ ) ]`. You probably want `if(obj2[\`${gender}_count\`])` – Arthur Aug 21 '17 at 08:37
  • @Arthur I see, is that how template literal work? I didn't proceed because I'm not confidence. Not only how to use template literal but the overall readability of the code. – Cecilia Chan Aug 21 '17 at 08:40
  • You don't really need template literal here.. (https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Template_literals). It's just like before `'count_' + gender` is identical to `\`count_${gender}`\` – Arthur Aug 21 '17 at 08:43
  • @Arthur any clue what's wrong here? I got unexpected token error https://pastebin.com/raw/7Nd61gsn – Cecilia Chan Aug 21 '17 at 09:08
  • I think this post will help you: https://stackoverflow.com/a/35902149/2929632 – Arthur Aug 21 '17 at 09:15

0 Answers0