All files / src/functions add.files.from.folder.ts

100% Statements 18/18
100% Branches 0/0
100% Functions 6/6
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    3x 3x       3x 14x     14x 20x 20x 20x               20x 20x     14x 16x       14x 4x     14x     3x  
'use strict';
 
import * as fs from 'fs';
import * as path from 'path';
 
import {ItemStat} from '../interfaces/item.stat.interface';
 
const addFilesFromFolder: Function = (files: string[], folder: string): string[] => {
	const subfolderNames: string[] = fs.readdirSync(folder);
 
	// PERFORMANCE: Single lstat call per item instead of two
	const itemStats: ItemStat[] = subfolderNames.map((name: string): ItemStat => {
		const fullPath: string = path.join(folder, name);
		const stat: fs.Stats = fs.lstatSync(fullPath);
		return {
			name,
			fullPath,
			isDirectory: stat.isDirectory()
		};
	});
 
	// Separate files and folders using cached stat results
	const subFiles: ItemStat[] = itemStats.filter((item: ItemStat): boolean => !item.isDirectory);
	const subFolders: ItemStat[] = itemStats.filter((item: ItemStat): boolean => item.isDirectory);
 
	// Add files to the array using native forEach
	subFiles.forEach((file: ItemStat): void => {
		files.push(file.fullPath);
	});
 
	// Process subfolders recursively
	subFolders.forEach((subFolder: ItemStat): void => {
		files = addFilesFromFolder(files, subFolder.fullPath);
	});
 
	return files;
};
 
export default addFilesFromFolder;