Skip to content

Instantly share code, notes, and snippets.

@westc
Last active April 15, 2023 04:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save westc/767681a206bb4aa768e6ac808a3b3a26 to your computer and use it in GitHub Desktop.
Save westc/767681a206bb4aa768e6ac808a3b3a26 to your computer and use it in GitHub Desktop.
quoteRegExp() - This is an example of overloading a function and annotating it with JSDoc.
/**
* @type {{
* (input: string): string;
* (input: string, returnRegExp: true): RegExp;
* (input: string, flags: string): RegExp;
* }}
*/
const quoteRegExp = function(input, flags) {
input = input.replace(/[/\-\\^$*+?.()|[\]{}]/g, '\\$&');
if (flags === true) flags = '';
return 'string' === typeof flags ? new RegExp(input, flags) : input;
};
@westc
Copy link
Author

westc commented Mar 8, 2023

You can also do the following but the names will not carry over (nor will any associated comments):

/**
 * @type {quoteRegExp_1 & quoteRegExp_2 & quoteRegExp_3}
 */
const quoteRegExp = function(input, flags) {
  input = input.replace(/[/\-\\^$*+?.()|[\]{}]/g, '\\$&');
  if (flags === true) flags = '';
  return 'string' === typeof flags ? new RegExp(input, flags) : input;
};
/**
 * @callback quoteRegExp_1
 * @param {string} input
 * @param {?false=} flags
 * @returns {string}
 */
/**
 * @callback quoteRegExp_2
 * @param {string} input
 * @param {true} flags
 * @returns {RegExp}
 */
/**
 * @callback quoteRegExp_3
 * @param {string} input
 * @param {string} flags
 * @returns {RegExp}
 */

const a = quoteRegExp('asdf');            // VS Code type hint: string
const b = quoteRegExp('asdf', undefined); // VS Code type hint: string
const c = quoteRegExp('asdf', null);      // VS Code type hint: string
const d = quoteRegExp('asdf', false);     // VS Code type hint: string
const e = quoteRegExp('asdf', true);      // VS Code type hint: RegExp
const f = quoteRegExp('asdf', 'g');       // VS Code type hint: RegExp

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment