diff --git a/lib/index.ts b/lib/index.ts index 5c67e54..66d0a19 100644 --- a/lib/index.ts +++ b/lib/index.ts @@ -7,7 +7,7 @@ class FilePath { public filename: string | undefined; /** An ordered array of folder names. folders[0] represents the root of the path. - * If absolute, it will be empty '' (required), if relative, it will be the folder reference '.' or '..' + * If absolute, it will be an empty string (required), if relative, it will be the folder reference '.' or '..' */ public folders: string[] = []; @@ -58,6 +58,14 @@ class FilePath { public get extension(): string | undefined { return this._extension; } + + public get isAbsolute(): boolean { + return this.folders[0] === ''; + } + + public get isRelative(): boolean { + return this.folders[0] !== ''; + } } export default FilePath; diff --git a/readme.md b/readme.md index 1cf22b4..8ae917e 100644 --- a/readme.md +++ b/readme.md @@ -124,3 +124,37 @@ console.log(path.folders, path.path); > ['..', 'this', 'is', 'relative'] > '../this/is/relative/file.jpeg; ``` + +### isAbsolute and isRelative + +Booleans indicating if the path is absolute or relative. Absolute paths only start with '/', +and the `path.folders[0] === ''`; + +Ex. + +```js + +const path = new FilePath('/this/is/a/file.jpeg'); +console.log(path.isAbsolute, path.isRelative) + +> true +> false + +path.path = 'this/is/a/file.jpeg'; +console.log(path.isAbsolute, path.isRelative) + +> false +> true + +path.path = './this/is/a/file.jpeg'; +console.log(path.isAbsolute, path.isRelative) + +> false +> true + +path.path = '../this/is/a/file.jpeg'; +console.log(path.isAbsolute, path.isRelative) + +> false +> true +``` diff --git a/tests/index.spec.ts b/tests/index.spec.ts index 8a60404..2d9d6d7 100644 --- a/tests/index.spec.ts +++ b/tests/index.spec.ts @@ -85,4 +85,22 @@ describe('FilePath', () => { expect(path.file).toEqual(undefined); expect(path.path).toEqual('/this/is/the/'); }); + + it('isAbsolute and isRelative', () => { + const path = new FilePath('/this/is/a/file.jpeg'); + expect(path.isAbsolute).toEqual(true); + expect(path.isRelative).toEqual(false); + + path.path = 'this/is/a/file.jpeg'; + expect(path.isAbsolute).toEqual(false); + expect(path.isRelative).toEqual(true); + + path.path = './this/is/a/file.jpeg'; + expect(path.isAbsolute).toEqual(false); + expect(path.isRelative).toEqual(true); + + path.path = '../this/is/a/file.jpeg'; + expect(path.isAbsolute).toEqual(false); + expect(path.isRelative).toEqual(true); + }); });