Skip to content

Commit

Permalink
[Refactor] re-implement 'isSubpath' without building a dynamic regex
Browse files Browse the repository at this point in the history
  • Loading branch information
skozin committed Jan 13, 2020
1 parent 89cde31 commit ed9c935
Showing 1 changed file with 9 additions and 7 deletions.
16 changes: 9 additions & 7 deletions src/core/importType.js
Expand Up @@ -29,13 +29,15 @@ function isExternalPath(path, name, settings) {
}

function isSubpath(subpath, path) {
const subpathRegExpSrc = escapeRegExp(subpath.replace(/[/]$/, ''))
const subpathRegExp = new RegExp(`${isAbsolute(subpath) ? '^' : '(?:^|/)'}${subpathRegExpSrc}(?:/|$)`)
return subpathRegExp.test(path)
}

function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
const normSubpath = subpath.replace(/[/]$/, '')
if (normSubpath.length === 0) {
return false
}
const left = path.indexOf(normSubpath)
const right = left + normSubpath.length
return left !== -1 &&
(left === 0 || normSubpath[0] !== '/' && path[left - 1] === '/') &&
(right >= path.length || path[right] === '/')
}

const externalModuleRegExp = /^\w/
Expand Down

0 comments on commit ed9c935

Please sign in to comment.