Skip to content

Instantly share code, notes, and snippets.

@jamestharpe
Created August 18, 2019 18:12
Show Gist options
  • Save jamestharpe/d84b5dcb79cb715f16afa8a2058fff5a to your computer and use it in GitHub Desktop.
Save jamestharpe/d84b5dcb79cb715f16afa8a2058fff5a to your computer and use it in GitHub Desktop.
Common root directory of a list of file paths using TypeScript
import { dirname, sep, resolve } from "path";
function commonRoot(...paths: string[]) {
return !paths || paths.length === 0
? undefined
: paths
.map(path => dirname(resolve(path)))
.reduce((prev, curr) => {
const prevParts = prev.split(sep);
const currParts = curr.split(sep);
return prevParts.filter((part, i) => part === currParts[i]).join(sep);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment