Skip to content

Commit

Permalink
feat: add isRelative helper (#17)
Browse files Browse the repository at this point in the history
  • Loading branch information
danielroe authored Mar 5, 2021
1 parent 7782d82 commit 63efb7b
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,15 @@ Check two paths are equal or not. Trailing slash and encoding are normalized bef
isSamePath('/foo', '/foo/')
```

### `isRelative`

Check if a path starts with `./` or `../`.

```ts
// Result: true
isRelative('./foo')
```

## License

[MIT](./LICENSE)
Expand Down
4 changes: 4 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ import { parseURL, stringifyParsedURL } from './parse'
import { QueryObject, parseQuery, stringifyQuery } from './query'
import { decode } from './encoding'

export function isRelative (inputStr: string) {
return ['./', '../'].some(str => inputStr.startsWith(str))
}

export function hasProtocol (inputStr: string, acceptProtocolRelative = false): boolean {
return /^\w+:\/\/.+/.test(inputStr) || (acceptProtocolRelative && /^\/\/[^/]+/.test(inputStr))
}
Expand Down
17 changes: 16 additions & 1 deletion test/utilities.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { hasProtocol } from '../src'
import { hasProtocol, isRelative } from '../src'

describe('hasProtocol', () => {
const tests = [
Expand All @@ -19,3 +19,18 @@ describe('hasProtocol', () => {
})
}
})

describe('isRelative', () => {
const tests = [
{ input: '/', out: false },
{ input: './/', out: true },
{ input: '../test', out: true },
{ input: 'https://', out: false }
]

for (const t of tests) {
test(t.input.toString(), () => {
expect(isRelative(t.input)).toBe(t.out)
})
}
})

0 comments on commit 63efb7b

Please sign in to comment.