toy
toy

Reputation: 12141

How can I reduce cyclomatic complexity from this piece of code?

I'm refactoring some legacy code. I get error from jshint about cyclomatic complexity which I'm trying to figure out how to fix the warning. The code is in node.js so anything in JavaScript is very much welcome.

  if (rawObj.title) {
    formattedObj.name = rawObj.title;
  }
  if (rawObj.urls && rawObj.urls.web) {
    formattedObj.url = rawObj.urls.web.project;
  }
  if (rawObj.photo) {
    formattedObj.image = rawObj.photo.thumb;
  }
  if (rawObj.category) {
    formattedObj.category = rawObj.category.name;
  }

It's really just checking if the property exists and map to a new object.

Upvotes: 3

Views: 407

Answers (1)

colecmc
colecmc

Reputation: 3318

Kind of late to the party but you (or others looking for ways to reduce cyclomatic-complexity) could go with an approach like this. It's kind of like the strategy pattern. Depending if you can or can't use ES6, will determine which setRawObjProp you should use.

function setFormObjName () {
  formattedObj.name = rawObj.title;
  console.log(arguments.callee.name,formattedObj);
}

function setFormObjURL () {
  formattedObj.url = rawObj.urls.web.project;
  console.log(arguments.callee.name,formattedObj);
}

function setFormObjImage () {
  formattedObj.image = rawObj.photo.thumb;
  console.log(arguments.callee.name,formattedObj);
}

function setFormObjCat () {
  formattedObj.category = rawObj.category.name;
  console.log(arguments.callee.name,formattedObj);
}

function setRawObjProp(obj) {
  var objectMap = new Map();

  objectMap
    .set('string1', setFormObjName)
    .set('string2', setFormObjURL)
    .set('string3', setFormObjImage)
    .set('string4', setFormObjCat);

  if (objectMap.has(obj)) {
    return objectMap.get(obj)();
  }
  else {
    console.log('error', obj); 
  }
}

/*
function setRawObjProp2(obj) {
  var objectMap = {
      'string1': setFormObjName,
      'string2': setFormObjURL,
      'string3': setFormObjImage,
      'string4': setFormObjCat,
  };

  if (objectMap.hasOwnProperty(obj)) {
    return objectMap.get(obj)();
  }
  else {
    console.log('error', obj); 
  }
}
*/

var rawObj = {
  title: 'string1',
  urls: {
    app: {
      project: 'some thing'
    },
    web: {
      project: 'string2'
    }
  },
  photo: {
    large: 'large',
    thumb: 'string3'
  },
  category: {
    name: 'string4',
    type: 'some type',
    id: 12345
  }
},

formattedObj = {
  title: '',
  urls: {
    web: {
      project: ''
    }
  },
  photo: {
    thumb: ''
  },
  category: {
    name: ''
  }
};

setRawObjProp('string1');
/* setRawObjProp2('string1') */

Upvotes: 1

Related Questions