Skip to content

Instantly share code, notes, and snippets.

@maxpatiiuk
Created April 1, 2024 02:45
Show Gist options
  • Save maxpatiiuk/7e160efc49332ed16ae699c637233288 to your computer and use it in GitHub Desktop.
Save maxpatiiuk/7e160efc49332ed16ae699c637233288 to your computer and use it in GitHub Desktop.
Remove blank, comment-only or import lines from a JavaScript source file
/**
* Remove blank, comment-only or import lines from a JavaScript source file.
*
* Perfect for getting a quick count of how many actual "content" lines there are in a file.
*
* @param {string} javaScript
* @returns string
*/
function reduce(javaScript) {
const reduced = javaScript
.split("\n")
.filter(
(line) =>
line.trim().length !== 0 &&
!line.trim().startsWith("//") &&
!line.trim().startsWith("/*") &&
!line.trim().startsWith("*"),
);
const importEndIndex = reduced.findIndex(
(line) => !line.startsWith("import "),
);
return reduced.slice(importEndIndex).join("\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment