3

The more "magic" your JavaScript library is, the less likely it is that you're able to use a documentation generator.

Is anyone aware of a documentation generator that allows documentation of functions with parameter shifting/parametric polymorphism?

function example(required, optional, callback) {
   if(typeof optional === 'function' && typeof callback === 'undefined') {
       callback = optional;
       optional = 'DEFAULT VALUE';
   }

   // do work here
}

Which can be called as follows:

example(required, optional, function() {
  // do work
});

example(required, function() {
  // do work
});

Any suggestions are appreciated, with the exception of "use a generic comment/documentation block".

This is related, but not a duplicate of: Document generic type parameters in JSDOC

Community
  • 1
  • 1
Jeff
  • 458
  • 6
  • 12

1 Answers1

4

It looks like JSDoc supports overloading of functions with the @name fun @name fun^2 I think the following communicates your intent clearly

/**
    @name example
    @function
    @param {string} required
    @param {Function} callback
 */
 /**
    @name example^2
    @function
    @param {string} required
    @param {string} [optional='DEFAULT VALUE']
    @param {Function} callback
 */
function example() {
    if(typeof optional === 'function' && typeof callback === 'undefined') {
       callback = optional;
       optional = 'DEFAULT VALUE';
    }

    // do work here
}

However, in your case, I think it would be easiest if you just switched your optional parameter to the end, then you won't need overloading

/**
 * @param required
 * @param {Function} callback
 * @param {String} [optional='DEFAULT VALUE'] 
 */
function example(required, callback, optional) {
   if (typeof optional === 'undefined') {
       optional = 'DEFAULT VALUE';
   }   
   // do work here
}
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
  • 1
    I have not tested this, however, you have proposed a solution that satisfied my requirements in addition to a workaround. This is what I look for in an answer. Thanks for your sleuthing. – Jeff Mar 21 '14 at 18:36