Switch 문을 레코드로 바꾸기 - Typescript

목차
* 📢 ANNOUNCEMENT
* 🚀 INTRO
* ⚙ IMPLEMENTATION
* 👨🏻‍💻 CODESANDBOX
* 🤔 CONCLUSION
* 🙏 THANK YOU

📢 공지!

Hello coding dudes and dudesses! Hope you are all well and healthy. It's been quite a difficult time around the globe. I haven't been active for some time. I want to announce that I will communicate with you (through blogs) more often and try to tackle coding, engineering and business with you. Without further ado, let's get into it!


🚀 소개

So, you probably came across a situation where you have something like this:

switch(someVariable: string) {
   case 'someValue': 
        ....
        break;
   case 'someOtherValue':
        ....
        break;
   case 'somethingElse':
        ....
        break;
   ...
}

You probably did, right? Well, there is nothing wrong about this, It is perfectly correct way of replacing the If statement. But we can notice that this can also get a bit hard to follow and manage. With the power of TypeScript we can actually make this even simpler.

⚙ [구현]

Let's consider that each case within the switch statement usually and in the best case has three lines of code.

case 'valueToCompareWith':       //first line
      someFunctionToExecute();  //line two
      break;                     //third line

Example
We have an assignment:

  • We should fetch some financial or product data using two different functions (handlers) that someone provided for us. Let's say getFinancialData() and getProductData().
  • For this occasion we are currently using the same indicator, let's call it dataHandlerIndicator and it will be of type 'financial' | 'product'.

Let's make a switch statement for this example

type DataType = 'financial' | 'product';
const dataHandlerFunction = (dataHandlerIndicator: DataType) => {
   switch(dataHandlerIndicator) {
      case 'financial':
         getFinancialData();
         break;
      case 'product':
         getProductData();
         break;
   }
} 

So, for these two different DataType types we have 6 lines of code handling it and making it fairly easy to read. If we had 3 types we would have 9 lines of code, and for 10 different data types, well we all understand maths, we will have ~ 30 lines of code, maybe even more if we add some additional logic to the case statement.

Let's simplify this by using Record!

// functions to be called
const getFinancialData = () => {
    console.log('Fetch financial data...');
}

const getProductData = () => {
    console.log('Fetch product data...');
}
// end functions to be called ...

type DataType = 'financial' | 'product';

const getDataSelector: Record<DataType, () => void> = {
   'financial': getFinancialData,
   'product': getProductData
}

const dataHandlerFunction = (dataHandlerIndicator: DataType) => {
   getDataSelector[dataHandlerIndicator]()
}

dataHandlerFunction('product'); // 'Fetch product data...'
dataHandlerFunction('financial'); // 'Fetch financial data...'
TRY OUT THE CODESANDBOX EXAMPLE

🤔 결론

Now, we can see that with the Record we have two lines of code describing the functions that will be called based on the DataType key value, and we have one line getDataSelector[dataHandlerIndicator]() that will call corresponding function based on the dataHandlerIndicator we pass to the function. Pretty neat, right!?

  • We reduced number of lines
  • Our code is much more readable
  • In order to add additional functionality, just update the Record with the new (key, value) pair, and that's it, you have a new selector for fetching new data based on the data type selector.

🙏 읽어주셔서 감사합니다!

Please leave a comment, tell me about you, about your work, comment your thoughts, connect with me!

☕ SUPPORT ME AND KEEP ME FOCUSED!



즐거운 해킹시간 되세요! 😊

좋은 웹페이지 즐겨찾기