/**
* Flattens a nested file path structure.
*
* @param {string} path The file path to flatten.
* @returns {string} The flattened file path, or null if the input is invalid.
*/
function flattenFilePath(path) {
if (typeof path !== 'string' || path.trim() === '') {
return null; // Basic input validation: check if it's a non-empty string
}
const parts = path.split(/[\\/]/); // Split by path separators
const flattened = parts.filter(part => part !== ''); // Remove empty strings from the array
return flattened.join('/'); // Join with forward slashes
}
/**
* Validates the flattened path.
*
* @param {string} flattenedPath The flattened path to validate.
* @returns {boolean} True if the path is valid, false otherwise.
*/
function isValidFlattenedPath(flattenedPath) {
if (typeof flattenedPath !== 'string' || flattenedPath.trim() === '') {
return false; //check if it's a non-empty string
}
if (!/^[a-zA-Z0-9_\-\/]+$/.test(flattenedPath)) { //check if contains only allowed characters
return false;
}
return true;
}
/**
* Processes a file path, flattening it and validating the result.
*
* @param {string} path The file path to process.
* @returns {string|null} The flattened and validated file path, or null if invalid.
*/
function processFilePath(path) {
const flattened = flattenFilePath(path);
if (flattened) {
if (isValidFlattenedPath(flattened)) {
return flattened;
} else {
return null; // Invalid flattened path
}
} else {
return null; // Invalid input path
}
}
Add your comment