UNPKG

makedrive

Version:
78 lines (62 loc) 1.79 kB
/** * Sync path resolver is a library that provides * functionality to determine 'syncable' paths * It exposes the following methods: * * resolve - This method takes two paths as arguments. * The goal is to find the most common ancestor * between them. For e.g. the most common ancestor * between '/dir' and '/dir/file.txt' is '/dir' while * between '/dir' and '/file.txt' would be '/'. * * resolveFromArray - This method works exactly like resolve but works for arrays of paths instead */ var pathResolver = {}; var dirname = require('./filer').Path.dirname; function getDepth(path) { if(path === '/') { return 0; } return 1 + getDepth(dirname(path)); } function commonAncestor(path1, depth1, path2, depth2) { if(path1 === path2) { return path1; } // Regress the appropriate path if(depth1 === depth2) { path1 = dirname(path1); depth1--; path2 = dirname(path2); depth2--; } else if(depth1 > depth2) { path1 = dirname(path1); depth1--; } else { path2 = dirname(path2); depth2--; } return commonAncestor(path1, depth1, path2, depth2); } pathResolver.resolve = function(path1, path2) { if(!path1 && !path2) { return '/'; } if(!path1 || !path2) { return path1 || path2; } var path1Depth = getDepth(path1); var path2Depth = getDepth(path2); return commonAncestor(path1, path1Depth, path2, path2Depth); }; pathResolver.resolveFromArray = function(paths) { if(!paths) { return '/'; } var resolvedPath, i; for(i = 1, resolvedPath = paths[0]; i < paths.length; i++) { resolvedPath = pathResolver.resolve(resolvedPath, paths[i]); } return resolvedPath; }; module.exports = pathResolver;