index.js 843 B

123456789101112131415161718192021222324252627282930313233
  1. 'use strict'
  2. const { sep: DEFAULT_SEPARATOR } = require('path')
  3. const determineSeparator = paths => {
  4. for (const path of paths) {
  5. const match = /(\/|\\)/.exec(path)
  6. if (match !== null) return match[0]
  7. }
  8. return DEFAULT_SEPARATOR
  9. }
  10. module.exports = function commonPathPrefix (paths, sep = determineSeparator(paths)) {
  11. const [first = '', ...remaining] = paths
  12. if (first === '' || remaining.length === 0) return ''
  13. const parts = first.split(sep)
  14. let endOfPrefix = parts.length
  15. for (const path of remaining) {
  16. const compare = path.split(sep)
  17. for (let i = 0; i < endOfPrefix; i++) {
  18. if (compare[i] !== parts[i]) {
  19. endOfPrefix = i
  20. }
  21. }
  22. if (endOfPrefix === 0) return ''
  23. }
  24. const prefix = parts.slice(0, endOfPrefix).join(sep)
  25. return prefix.endsWith(sep) ? prefix : prefix + sep
  26. }