Search code examples
javascriptnode.jsecmascript-5

Is there a JavaScript documentation generator that supports parameter shifting and "polymorphism"?


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


Solution

  • 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
    }