Skip to content

Instantly share code, notes, and snippets.

@threepointone
Last active February 4, 2021 09:30
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save threepointone/9947e91887063b67155aa7bc06990342 to your computer and use it in GitHub Desktop.
Save threepointone/9947e91887063b67155aa7bc06990342 to your computer and use it in GitHub Desktop.
converted a function to a generator; simpler, more efficient, cooler.
// recursively get all files in a folder
function* getAllFiles(dirPath: string): Iterable<string> {
for (const file of fs.readdirSync(dirPath)) {
const pathToCheck = path.join(dirPath, file);
if (fs.statSync(pathToCheck).isDirectory()) {
if (file !== 'node_modules') {
yield* getAllFiles(pathToCheck);
}
} else {
yield pathToCheck;
}
}
}
// recursively get all files in a folder
function getAllFiles(dirPath: string, arrayOfFiles: string[] = []) {
const files = fs.readdirSync(dirPath);
files.forEach(function (file) {
const pathToCheck = path.join(dirPath, file);
if (fs.statSync(pathToCheck).isDirectory()) {
if (file !== 'node_modules') {
arrayOfFiles = getAllFiles(pathToCheck, arrayOfFiles);
}
} else {
arrayOfFiles.push(pathToCheck);
}
});
return arrayOfFiles;
}
// recursively get all files in a folder
-function getAllFiles(dirPath: string, arrayOfFiles: string[] = []) {
- const files = fs.readdirSync(dirPath);
-
- files.forEach(function (file) {
+function* getAllFiles(dirPath: string): Iterable<string> {
+ for (const file of fs.readdirSync(dirPath)) {
const pathToCheck = path.join(dirPath, file);
if (fs.statSync(pathToCheck).isDirectory()) {
if (file !== 'node_modules') {
- arrayOfFiles = getAllFiles(pathToCheck, arrayOfFiles);
+ yield* getAllFiles(pathToCheck);
}
} else {
- arrayOfFiles.push(pathToCheck);
+ yield pathToCheck;
}
- });
-
- return arrayOfFiles;
+ }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment