Created
August 18, 2019 18:12
-
-
Save jamestharpe/d84b5dcb79cb715f16afa8a2058fff5a to your computer and use it in GitHub Desktop.
Common root directory of a list of file paths using TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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