All files / src/functions list.subfolders.by.name.ts

100% Statements 17/17
100% Branches 2/2
100% Functions 4/4
100% Lines 16/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41    3x 3x       3x 89x   89x     89x 204x 204x 204x               204x     89x 89x 9x     80x       89x     3x  
'use strict';
 
import * as fs from 'fs';
import * as path from 'path';
 
import {ItemStat} from '../interfaces/item.stat.interface';
 
const listSubfoldersByName: Function = (root: string, folderName: string): string[] => {
	let folders: string[] = [];
 
	const subfolderNames: string[] = fs.readdirSync(root);
 
	// PERFORMANCE: Single lstat call per item instead of filtering twice
	const itemStats: ItemStat[] = subfolderNames.map((name: string): ItemStat => {
		const fullPath: string = path.join(root, name);
		const stat: fs.Stats = fs.lstatSync(fullPath);
		return {
			name,
			fullPath,
			isDirectory: stat.isDirectory()
		};
	});
 
	// Filter only directories using cached stat results
	const subfolders: ItemStat[] = itemStats.filter((item: ItemStat): boolean => item.isDirectory);
 
	// Process subfolders using native forEach
	subfolders.forEach((subfolder: ItemStat): void => {
		if (folderName === subfolder.name) {
			folders.push(subfolder.fullPath);
		} else {
			// Recursively search subfolders and combine results using native concat
			folders = folders.concat(listSubfoldersByName(subfolder.fullPath, folderName));
		}
	});
 
	return folders;
};
 
export default listSubfoldersByName;