getPaths.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. /**
  7. * @param {string} path path
  8. * @returns {{paths: string[], segments: string[]}}} paths and segments
  9. */
  10. module.exports = function getPaths(path) {
  11. if (path === "/") return { paths: ["/"], segments: [""] };
  12. const parts = path.split(/(.*?[\\/]+)/);
  13. const paths = [path];
  14. const segments = [parts[parts.length - 1]];
  15. let part = parts[parts.length - 1];
  16. path = path.substring(0, path.length - part.length - 1);
  17. for (let i = parts.length - 2; i > 2; i -= 2) {
  18. paths.push(path);
  19. part = parts[i];
  20. path = path.substring(0, path.length - part.length) || "/";
  21. segments.push(part.slice(0, -1));
  22. }
  23. part = parts[1];
  24. segments.push(part);
  25. paths.push(part);
  26. return {
  27. paths: paths,
  28. segments: segments
  29. };
  30. };
  31. /**
  32. * @param {string} path path
  33. * @returns {string|null} basename or null
  34. */
  35. module.exports.basename = function basename(path) {
  36. const i = path.lastIndexOf("/"),
  37. j = path.lastIndexOf("\\");
  38. const p = i < 0 ? j : j < 0 ? i : i < j ? j : i;
  39. if (p < 0) return null;
  40. const s = path.slice(p + 1);
  41. return s;
  42. };