javascript function argument handling


/ Published in: JavaScript
Save to your folder(s)

/*
* A little help function for when I'm creating functions
*
* When I pluck values from function arguments I tend to
* write content of this function repeatedly.
*
* e.g.
* a = arguments
* this.id = arg(a, 0)
* this.name = arg(a, 3)
*
* this.id == 6
* this.name == null
*/


Copy this code and paste it in your HTML
  1. /*
  2.  * A little help function for when I'm creating functions
  3.  *
  4.  * When I pluck values from function arguments I tend to
  5.  * write content of this function repeatedly.
  6.  *
  7.  * e.g.
  8.  * a = arguments
  9.  * this.id = arg(a, 0)
  10.  * this.name = arg(a, 3)
  11.  *
  12.  * this.id == 6
  13.  * this.name == null
  14.  */
  15. function arg(_a, ia, def, returnArray) {
  16. var v = null
  17.  
  18. // if ia is an array, find the
  19. // first correct definition
  20. if (ia.constructor == Array) {
  21. /*
  22. * Each item is checked. if the
  23. * item in the array is
  24. * a definition within the oaet
  25. * arguments or object - pass it
  26. */
  27. for(var i=0; i<ia.length; i++) {
  28. if(_a[ia[i]]){
  29.  
  30. v = _a[ia[i]];
  31. break;
  32. }
  33. }
  34. }
  35. else {
  36. // if ia is just a value
  37. if(_a[ia]) v = _a[ia];
  38. }
  39.  
  40. if( (v == null) && (def != undefined) ) {
  41. v = def
  42. }
  43.  
  44. if(returnArray){
  45. return [v, ia[i]]
  46. }
  47. else
  48. {
  49. return v
  50. }
  51.  
  52. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.