Saturday, October 20, 2012

a try/catch block, a case statement, and a string to number conversion, all within a chunk of a Jasmine widget

castStringToInteger: function (string) {
   var self = this;
   self.options.Translation = "Sacrebleu!";
   try {
      var integer = parseInt(string);
      if (integer > -9999999) {
         self.options.Number = integer;
         self.castIntegerToString();
      } else {
         throw "conversion is bad";
      }
   }
   catch (err) {
   }
},
castIntegerToString: function () {
   var self = this;
   switch (self.options.Number) {
      case 0:
         self.options.Translation = "zéro";
         break;
      case 1:
         self.options.Translation = "un";
         break;
      case 2:
         self.options.Translation = "deux";
         break;
      case 3:
         self.options.Translation = "trois";
         break;
      case 4:
         self.options.Translation = "quatre";
         break;
      case 5:
         self.options.Translation = "cinq";
         break;
      case 6:
         self.options.Translation = "six";
         break;
      case 7:
         self.options.Translation = "sept";
         break;
      case 8:
         self.options.Translation = "huit";
         break;
      case 9:
         self.options.Translation = "neuf";
         break;
   }
},
options: {
   Number: null,
   Translation: null
}

 
 

Note

  1. alert(err); inside the catch block would bubble our exception up to the user, but I have left this out instead opting to swallow the exception and just say "Sacrebleu!" when things don't go as planned.
  2. var float = parseFloat(string); is the way to handle a number with a decimal in it.

No comments:

Post a Comment