Home > Mobile >  How can i abstract this if, else statement?
How can i abstract this if, else statement?

Time:12-11

if (active)
   classes.container = classes.container.replace(
     classModifiers.active.container.remove,
     classModifiers.active.container.add
   );
 else
   classes.container = classes.container.replace(
     classModifiers.active.container.add,
     classModifiers.active.container.remove
   );

 if (active)
   classes.icon = classes.icon.replace(
     classModifiers.active.icon.remove,
     classModifiers.active.icon.add
   );
 else
   classes.icon = classes.icon.replace(
     classModifiers.active.icon.add,
     classModifiers.active.icon.remove
   );

 if (active)
   classes.badge = classes.badge.replace(
     classModifiers.active.badge.remove,
     classModifiers.active.badge.add
   );

 else
   classes.badge = classes.badge.replace(
     classModifiers.active.badge.add,
     classModifiers.active.badge.remove
   );

I don`t know how to abstract it. I have repeat it 3 times because i couldn't find another solution. Help me guys to figure it out. Any suggestions?

CodePudding user response:

const replacer = (entity, active) => {
  if (active) {
    return replace(classModifiers.active[entity].remove, classModifiers.active[entity].add);
  } else {
    return replace(classModifiers.active[entity].add, classModifiers.active[entity].remove);
  }
};
classes.container = replacer('container', active);
classes.icon = replacer('icon', active);
classes.badge = replacer('badge', active);

May be, like this?

CodePudding user response:

classes.container = doMagic(classes.container, "container");
classes.icon = doMagic(classes.icon, "icon");
classes.badge = doMagic(classes.badge, "badge");

const doMagic = (element, fieldName) =>
    element.replace(
        classModifiers.active[fieldName][active ? "remove" : "add"],
        classModifiers.active.container[active ? "add" : "remove"]
    )

CodePudding user response:

You can access an object property using the [] notation Like this:

['container', 'icon', 'badge'].forEach(pname => {
    if (active)
        classes.container = classes.container.replace(
            classModifiers.active[pname].remove,
            classModifiers.active[pname].add);
    else 
        classes.container = classes.container.replace(
            classModifiers.active[pname].add,
            classModifiers.active[pname].remove);
})
  • Related