Created
June 24, 2024 16:36
-
-
Save souporserious/c5d0553897ab95fd9b1c000cf634d8b2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function reformatJsDocComment(comment, maxWidth = 80) { | |
// Extract the content of the JSDoc comment | |
const content = comment | |
.split('\n') | |
.filter(line => line.trim() !== '/**' && line.trim() !== '*/') // TODO: handle inline JS Doc | |
.map(line => line.replace(/^\s*\/?\**\s?/g, '').replace(/\s*\*\/?$/, '').trim()) | |
.join(' '); | |
// Split the content into words | |
const words = content.split(/\s+/); | |
// Reformat the content to fit within the specified width | |
let reformattedComment = '/**\n'; | |
let currentLine = ' *'; | |
for (const word of words) { | |
if ((currentLine + ' ' + word).length > maxWidth) { | |
reformattedComment += currentLine + '\n'; | |
currentLine = ' * ' + word; | |
} else { | |
currentLine += ' ' + word; | |
} | |
} | |
// Add the last line and ensure proper closing of the JSDoc comment | |
if (currentLine.trim() !== '*') { | |
reformattedComment += currentLine + '\n'; | |
} | |
reformattedComment += ' */'; | |
return reformattedComment; | |
} | |
// Example usage | |
const jsDocComment = `/** | |
* This is a sample JS Doc comment that will be reformatted to fit within a specified character width. | |
* It supports multiple lines and will ensure that the resulting comment is properly formatted. | |
*/`; | |
console.log(reformatJsDocComment(jsDocComment, 40)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment