1. /**
  2. * Flattens a nested file path structure.
  3. *
  4. * @param {string} path The file path to flatten.
  5. * @returns {string} The flattened file path, or null if the input is invalid.
  6. */
  7. function flattenFilePath(path) {
  8. if (typeof path !== 'string' || path.trim() === '') {
  9. return null; // Basic input validation: check if it's a non-empty string
  10. }
  11. const parts = path.split(/[\\/]/); // Split by path separators
  12. const flattened = parts.filter(part => part !== ''); // Remove empty strings from the array
  13. return flattened.join('/'); // Join with forward slashes
  14. }
  15. /**
  16. * Validates the flattened path.
  17. *
  18. * @param {string} flattenedPath The flattened path to validate.
  19. * @returns {boolean} True if the path is valid, false otherwise.
  20. */
  21. function isValidFlattenedPath(flattenedPath) {
  22. if (typeof flattenedPath !== 'string' || flattenedPath.trim() === '') {
  23. return false; //check if it's a non-empty string
  24. }
  25. if (!/^[a-zA-Z0-9_\-\/]+$/.test(flattenedPath)) { //check if contains only allowed characters
  26. return false;
  27. }
  28. return true;
  29. }
  30. /**
  31. * Processes a file path, flattening it and validating the result.
  32. *
  33. * @param {string} path The file path to process.
  34. * @returns {string|null} The flattened and validated file path, or null if invalid.
  35. */
  36. function processFilePath(path) {
  37. const flattened = flattenFilePath(path);
  38. if (flattened) {
  39. if (isValidFlattenedPath(flattened)) {
  40. return flattened;
  41. } else {
  42. return null; // Invalid flattened path
  43. }
  44. } else {
  45. return null; // Invalid input path
  46. }
  47. }

Add your comment