DEV Community

loading...

Discussion on: A New Coding Style for Switch Statements in JavaScript/TypeScript

Collapse
john_papa profile image
John Papa

Reading this again (it's good, well done Bryan!).

I've been thinking about switch statements that collect a value so it can be returned at the end. imagine this ... which does not work for a few reasons.


let result = undefined;

switch (body.type) {

  case 'isBasic': {
    const entry = getBasicEntry(body.id);
    console.log(`Processing basic entry "${entry.name}"`);
    result = doBasicProcessing(entry);
    break;
  }

  case 'isCustom': {
    const entry = getCustomEntry(body.id);
    console.log(`Processing custom entry "${entry.name}"`);
    result =doCustomprocessing(entry);
    break;
  }

  default: {
    result = undefined;
  }

  return result;
}

The idea is to collect the result, then return it at the end. I'm not fond of this type of code with the let up top and then making sure each case handles a value. Any thoughts on what you do here?

Collapse
nebrius profile image
Bryan Hughes Author

This is a great insight! I combined this with a post above and created a little helper module: npmjs.com/package/conditional-reduce

Code looks like:

console.log(conditionalReduce('dog', {
  dog: () => 'Dogs are great pets',
  cat: () => 'Cat\'s are also great'
})); // Prints "Dogs are great pets"
Collapse
john_papa profile image
John Papa • Edited

So with that ... the code would be somehtng like this, for the example you and I used first. RIght?

let whatHappened = conditionalReduce(body.type, {
  'isBasic': () => {
    const entry = getBasicEntry(body.id);
    console.log(`Processing basic entry "${entry.name}"`);
    result doBasicProcessing(entry);
  },
  'isCustom': () => {
    const entry = getCustomEntry(body.id);
    console.log(`Processing custom entry "${entry.name}"`);
    return doCustomprocessing(entry);
  });
Thread Thread
nebrius profile image
Bryan Hughes Author

A few syntax issues aside, yes ;-)

It would look like:

let whatHappened = conditionalReduce(body.type, {
  'isBasic': () => {
    const entry = getBasicEntry(body.id);
    console.log(`Processing basic entry "${entry.name}"`);
    return doBasicProcessing(entry);
  },
  'isCustom': () => {
    const entry = getCustomEntry(body.id);
    console.log(`Processing custom entry "${entry.name}"`);
    return doCustomprocessing(entry);
  }
});
Thread Thread
john_papa profile image
John Papa

yeah, i figured the dev.to editor wouldn't protect me and that you'd forgive those mistakes :)