Skip to content

Instantly share code, notes, and snippets.

@Xetera
Last active February 12, 2019 06:28
Show Gist options
  • Save Xetera/689b08b99c94e5b4cf9e256da9e9a723 to your computer and use it in GitHub Desktop.
Save Xetera/689b08b99c94e5b4cf9e256da9e9a723 to your computer and use it in GitHub Desktop.
Basic glob function
const partition = (func, array) => array.reduce(([pass, nopass], item) => {
if (func(item)) {
return [[...pass, item], nopass]
}
return [pass, [...nopass, item]]
}, [[], []]);
const glob = async (path, regex) => {
const dirContent = await fsp.readdir(path, {withFileTypes: true})
const [folders, files] = partition(file => file.isDirectory(), dirContent)
const matchingFiles = files.reduce((all, file) => {
if (!regex.test(file.name)) {
return all;
}
const filePath = path ? join(path, file.name) : file.name;
return [...all, filePath];
}, []);
const rest = await folders.reduce(async (all, folder) => {
const previous = await all;
const folderPath = join(path, folder.name);
const globbed = await glob(folderPath, regex);
return [...previous, ...globbed];
}, []);
return [...matchingFiles, ...rest]
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment