Skip to content

Instantly share code, notes, and snippets.

@zionsg
Last active September 16, 2022 08:43
Show Gist options
  • Save zionsg/4e135eda6b4bb646d01d9beca4ab30e7 to your computer and use it in GitHub Desktop.
Save zionsg/4e135eda6b4bb646d01d9beca4ab30e7 to your computer and use it in GitHub Desktop.
Suggested order of module members in Node.js
// Import modules
const crypto = require('crypto');
/**
* Sample module showing suggested order of declaration for module members in Node.js
*
* Suggested order:
* - Constants before Properties before Methods
* - Public before Private
*
* Usage for this module:
* const sampleModule = require('suggested-order-of-module-members.js');
* console.log(sampleModule.SGP, sampleModule.getUuid());
*
* @link https://gist.github.com/zionsg - suggested-order-of-module-members.js
* @link See also SuggestedOrderOfClassMembers.php in https://gist.github.com/zionsg/5e21d79bea3d150dac5625ec84d94eed
* @link https://jsdoc.app/ used for documentation
* @returns {Object}
*/
module.exports = (function () {
/** @type {Object} Self reference - all public properties/methods are stored here & returned as public interface. */
const self = {};
/** @type {string} UTC timezone. */
const UTC = '+00:00';
/** @type {int} Do not use `var` to declare variables. */
let startTime = 0;
/**
* Singapore timezone
*
* @public
* @type {string}
*/
self.SGP = '+08:00';
/**
* Get UUID v4 string
*
* @public
* @returns {string} E.g. '123e4567-e89b-12d3-a456-426614174000'.
*/
self.getUuid = function () {
return crypto.randomUUID();
};
/**
* Get current timestamp in ISO 8601 format
*
* @private
* @returns {string}
*/
function getTimestamp() {
return (new Date()).toISOString();
}
/**
* Initialization
*
* Run at the end after all properties/methods have been declared instead
* of creating a `function init()` which may be hard to find if this module
* has many lines of code with the possibility of forgetting to run it.
*/
(async function init() { // async in case need to use await
startTime = Date.now();
})();
// Return public interface of IIFE (Immediately Invoked Function Expression)
return self;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment