News for hackers. Stuff that matters.
Re:Type Checking in JavaScript by tomcdonnell on Wednesday November 06, 2013 @08:20AM (#6682516)
Here's how I do type checking in Javascript.

  function doStuffWithAVarietyOfParameters(s, a, b, i, ni, p)
  {
     var f = 'contractCategoriesAndAddExpandButtons()';
     UTILS.checkArgs(f, arguments, ['string', 'array', 'boolean', 'int', 'negativeInt', 'Particle']);
  
     // Do stuff.
  }
For functions with many parameters, I like to pass the parameters inside an object and give the keys descriptive names.

  function doStuffWithAVarietyOfParameters(o)
  {
     var f = 'contractCategoriesAndAddExpandButtons()';
     UTILS.validator.checkObject
     (
        o,
        {
           arrayParam      : 'array'      ,
           boolParam       : 'boolean'    ,
           nullOrFloatParam: 'nullOrFloat',
           particleParam   : 'Particle'   ,
           positiveIntParam: 'positiveInt',
           stringParam     : 'string'
        }
     );
  
     // Do stuff.
  }
Both functions will throw an exception if the arguments list is not as expected. The code can be found via the links below.

https://github.com/tomcdonnell/lib_tom/blob/master/js/utils/...

https://github.com/tomcdonnell/lib_tom/blob/master/js/utils/...

I do type checking similarly in PHP.

http://tomcdonnell-tech.blogspot.com.au/2011/09/favourite-ph...

There are no comments on this comment yet.