Monday, November 3, 2014

Using objects for switch statements

I ran across a post where the author wished switch statements returned a value. The switch statement has always looked to me like a poor choice in programming. It seems like we should be able to use polymorphism instead of what is another version of a long if/else chain. However, there are cases when we could be over-designing and a switch statement would do the job.
// Not valid ECMAScript
var color = switch(x) {
  case   1: 
    'blue' ; break;
  case   2: 
    'red'  ; break;
  default : 
    'green';
};

The author, Dusan Jovanovich, proposed a cond function in the likes of lisp
cond( x, 
      1, 'blue', 
      2, 'red', 
      'green' );
Since lisp is the language where non-primitives are lists, and JavaScript is the language where non-primitives are basically maps, I would suggest a cond function that feels more like JavaScript.
function cond(val, cases, fallback, scope) {
    var theCase = cases.hasOwnProperty(val) ? cases[val] : fallback;
    return typeof theCase == "function" ? 
        theCase.call(scope || this, val) : 
        theCase; 
}
So that the previous cond call would look like:
var color = cond(x , {
   1: 'blue',
   2: 'red',
}, 'green');
One of the benefits of this function is that you can pass functions to each condition, so that we get almost all functionality of a switch:
jQuery('a').each(function(){
 switch(x) {
  case 1: 
    $(this).css({ color: 'blue'});
    $this.slideDown();
    break ;
  case 2: 
    $(this).css({ color: 'red'});
    $this.slideUp();
    break ;
  default : 
    $(this).css({ color: 'green'});
 }
});

// Could become
jQuery('a').each(function(){
  cond(x, {
    1: function() {
        $(this).css({ color:'blue'});
        $(this).slideDown();
    },
    2: function() {
        $(this).css({ color:'red'});
        $(this).slideUp();
    },
  }, function() {
        $(this).css({ color:'green'});
  }, this);
});
If you have multiple cases where the almost the same thing needs to happen (fallthroughs), the switched value is passed to each of the conditions, so you could nest them. At this point, this probably would not be a good idea, but here it goes anyway.
jQuery('a').each(function(){
  // Save 'this' instead of passing in a scope in this case
  var $this = $(this);
  
  function fallThrough12(y) {       
      cond(y, {
           1: function() {
              $this.css({ color:'blue'});
           }
           2: function() {
              $this.css({ color:'red'});
           }
      });
      $this.slideDown();
  }
  cond(x, {
    1: fallThrough12,
    2: fallThrough12,
    3: function() {
        $this.css({ color:'yellow'});
        $this.fadeOut();
    }
  }, function() {
        $this.css({ color:'green'});
  });

24 comments:

  1. Hulu supports a wide variety of devices that you can use to stream with us. enter hulu activation code You can activate any of them at any time, as well as remove them from your account.Hulu Activation code will be on your TV when you open Hulu App. hulu.com/activate If your account required activation then it will display on your screen then use online. Hulu Plus is available for streaming on popular gaming consoles like PlayStation 3 (PS3), Xbox 360 and Roku, as well as on the computer. By downloading the Hulu Plus application and activating your account, you can stream television shows and movies from the Hulu site. hulu.com/activate visit hulu activate now.

    ReplyDelete
  2. Steps to Activate Avg retail enlistment Once you install AVG retail activation on your framework, you require to activate it as without activation it is extraordinary to get its feature. avg.com/retail In this way, enact AVG antivirus by following given advances carefully.Avg is a well- known name in the field of virus protection. The reason for which this name is common among all end users is its free antivirus and malware protection.It not only sounds avg.com/retail free but it provides a lot more with no money. It scans for virus and malware.

    ReplyDelete
  3. System Mechanic Free keeps your PC running at peak performance and stability with advanced PC optimization, repair and maintenance features. system mechanic To install the most current version of System Mechanic Ultimate Defense, download the System Mechanic download manager via your internet.System Mechanic is the essential PC performance package that helps you automatically fix and speed up your PC. system mechanic System Mechanic is the most effective way to restore and maintain maximum PC speed and stability.

    ReplyDelete

  4. If your computer does not have the CD-ROM drive or you do not have the Setup CD, follow the steps given below. Visit canon.com/ijsetup Click Set Up. Either type in the model name of your printer, or click the first two letters shown under First Letters.The Canon printer enhances scan functionality, and includes a robust security feature set. Using a Canon printer service phone, you can get a full installation of the Canon printer and go to the installed Canon printer to download the canon.com/ijsetup driver.

    ReplyDelete

  5. Go to Amazon.com/mytv and create your Amazon account, if you already have an account then sign in to your account. Now enter the activation or verification code in the next screen that is in front of you. You are now ready to enjoy a lot of amazing and great movies and shows on your smart TV.Amazon.com/mytv is a registration portal of Amazon Prime from which members can watch thousands of movies and TV shows for free from their device some features require a premium subscription. The instant video service can only be watched after registering your device with a simple subscription code.Amazon.com/mytv is considered one of the most reliable web portals for the activation of Prime Video on your Smart TV. After successful registration, choose a TV cable provider’s network, sign in to your account, and start watching excellent Amazon Prime content on your Smart TV device.

    ReplyDelete
  6. Enter the link Amazon mytv enter code on your browser. Input your login details to log in to your Amazon Prime video account. A new screen will open which will ask for the “ Amazon Prime Verification Code . Amazon.com/mytventercode Amazon Prime is a subscription service that caters to the media needs of people through the platform. Notifies visitors about topics such as Register TV, Amazon Prime TV, and MyTV code. To register your device on the Amazon website you go to our website and enter the given code. The program requires the customer to have an Amazon account and a streaming device or TV. amazon mytv Amazon Prime Video is available on almost all streaming devices like Roku, Amazon Fire TV, Chromecast. For this, you just have to go to Amazon with the help of the amazon activation code. You can visit our website for details of the entire process. You can do this by installing the Video application on your smart TV, or the digital media player or video game console connected to your TV by visiting the link provided by us in the de cription.

    ReplyDelete
  7. if you want to watch anime online for free then you must consider these sites AnimeFlix and GoGoAnime

    ReplyDelete
  8. "mcafee is an antivirus software providers that secure your computer for virus , worms ,trojens and other mailcious program .it provides full range of
    security product like antivirus , firewall etc .you have to do mcafee antivirus download "

    ReplyDelete
  9. Amazon is an American multinational technology company which focuses on e-commerce, cloud computing, digital streaming, and artificial intelligence. It is one of the Big Five companies in the U.S. information technology industry, along with Google, Apple, Microsoft, and Facebook. amazon .com

    ReplyDelete
  10. Are you facing trouble with youtube tv activation on your Roku streaming device? Looking for helpdesk services for Roku? Don't get worried anymore. Now activate youtube on roku using tv.youtube.com/start code . Talk to our experts through live chat process. Get in touch with us for more information.

    ReplyDelete
  11. Thanks for sharing this blog here. It seems really very informative.

    Get solution to activate Roku streaming device using roku com link .

    tv.youtube.com/start/roku

    ReplyDelete
  12. Thanks for giving a wonderful article. If you want to promote your blog page or your product or your business then go for bulk sms service Chennai, they provide the best bulk sms service.

    bulk sms in bangalore | bulk sms explicit Bangalore | promotional sms provider | bulk sms reseller mysuru | SMS API | bulk sms gateway | sms implicit

    ReplyDelete
  13. 먹튀 검증 I'm going to see a good article! I want to share some good information! I come and go often~!

    ReplyDelete
  14. Our team of experts that can help you to provide services to activate roku streaming device using roku com link enter code.

    tv.youtube.com/start/roku
    roku com link
    amazon.com/mytv
    afrikastv roku

    ReplyDelete
  15. You no longer need to look for Arlo Com Login links all over the internet. Arlo Login - Arlo Pro Login - +1-818-824-4939 - arlo login

    ReplyDelete
  16. Do you have problems with the Arlo firmware upgrade failing? And you're looking for a simple way to solve this problem?
    how do i update my arlo camera firmware?

    ReplyDelete
  17. How to Delete AOL Account, You cannot delete your AOL mail account without the last of all AOL accounts, which means you lose access to all AOL services and products, including AIM instant messengers. Additionally, your email and address guidelines will be completely deleted after 90 days; you cannot restore your account after 90 days. If you log in with your AOL username and password, you can reactivate AOL and get deals with eBooks again. For More Link Below_ How to Delete AOL Account

    ReplyDelete
  18. Family Tree Maker Download
    As the name suggests, this is a freeware program that you can use to download and organize your family tree. It has a simple interface that is easy to navigate. The best thing about it is that it allows you to import data from Ancestry, Family Search, Heritage, Rootsier and other sites in a variety of formats including GED COM. Once imported, you can view your family tree in different ways including by country, state or county and also export it as an image file.

    ReplyDelete