0
Answered

How would you reduce this loop/switch case?

John Hamman 2 months ago updated by Ryan DeVault 1 month ago 4

Hi,  I am looking at a better way of handling this in Javascript.  I think refactoring it is needed.

 I have a data object that contains data that I need to split into a few different objects, which will each later be submitted to different API calls (fetch). 

inputData = { Contact__name :"John Doe", OtherContact__name: "Jane Smith", OtherContact2__name: "Dave Jones", Company__id: "1234"}

and I have a function that does the following that I think could be done better with a map/reducer/filter, but I am not sure how:

NOTE: 

  • All inputData Keys have the class name + '__' + property key (i.e. Contact__name)
  • Sometimes "OtherContact" may have multiple extra contacts that are numbered like: 'OtherContact2__name' or 'OtherContact3__name'.  I am still figuring out how I can deal with extra contacts.
  • Contact and OtherContact items have the same properties, whereas Company and Custom have unique ones.
const sortInputIntoObjects = (_inputData) => {
  let subkey = [];
  const tempArr = [];
  let ContactObj = {}, OtherContact = {}, Company = {}, Custom={};
  for (key in _inputData) {
    subkey = key.split('__');
    switch (subkey[0]) {
      case 'Contact': {
           // add to "Contact Object"
          ContactObj[subkey[1]] = _inputData[key];
        break;
      }   
      case 'OtherContact': {
        const numberPresent = subkey[0].match(REGEX_NUMBER);
        let ocKeyNum = 0;
        if (numberPresent !== null) {
          ocKeyNum = parseInt(numberPresent[0]);
        }
        
        if (ocKeyNum === null) {
          ocKeyNum = 0;
        }
        else { ocKeyNum = - 1; }
          
        OtherContact[subkey[1]] = _inputData[key];
        
        //ignore, still trying to figure out what to do with extra contacts
        tempArr[ocKeyNum] = OtherContact[subkey[1]];
        break;
      }
      case 'Company': {
          Company[subkey[1]] = _inputData[key];
        break;
      }
      default: {
          Custom[subkey[1]] = _inputData[key];
      }
    }
  }
};
Answered

Hi!

To be honest with you, I don't see a reason to change something in it. Yes, it may look a little messy, but so does the format of the input. Without changing the input and possibly, the output as well, this method wouldn't become much better. If there are others similar to this one, then maybe it's worth making some sort of data mapping. Otherwise, you would see similar lines in my own code.

Hello John,

I am unsure if this is any better but I just attempted to break out some of the functionality into separate functions

const calcOcKeyNum = (numberPresent) => {
  let ocTemp = 0
  if(numberPresent !== null){
    let temp = parseInt(numberPresent[0])
    ocTemp = temp !== null ? temp : -1
  }
  return ocTemp;
}

const sortInputIntoObjects = (_inputData) => {
  let subkey = [];
  // const tempArr = [];
  let ContactObj = {}, OtherContact = {}, Company = {}, Custom = {};
  const addToObject = (obj) => obj[subkey[1]] = _inputData[key];

  for (key in _inputData) {
    subkey = key.split('__');
    switch (subkey[0]) {
      case 'Contact': {
        addToObject(ContactObj);
        break;
      }
      case 'OtherContact': {
        addToObject(OtherContact)

        //ignore, still trying to figure out what to do with extra contacts
        // let ocKeyNum = calcOcKeyNum(subkey[0].match(REGEX_NUMBER))
        // tempArr[ocKeyNum] = OtherContact[subkey[1]];
        break;
      }
      case 'Company': {
        addToObject(Company);
        break;
      }
      default: {
        addToObject(Custom);
      }
    }
  }
};
+1

The code has become more compact, but I don't think there was any improvement in readability. In fact, it becomes harder to grasp what this method is doing because:

1. You now have a break in mental context - you have to travel mentally to methods calcOcKeyNum and addToObject to check what they do (it's still not obvious.)

2. The addToObject method is not self-contained, which makes it even harder to grasp its logic.

I know this thread wasn't for my code but thank you for the feedback on my response.