pathDiff method

String pathDiff (String url, String baseUrl)

Returns the difference between 2 paths to create a relative path

Example: url = 'a/' baseUrl = 'a/b/' returns '../' url = 'a/b/' baseUrl = 'a/' returns 'b/'

Implementation

String pathDiff(String url, String baseUrl) {
  final UrlParts baseUrlParts = extractUrlParts(baseUrl);
  int i;
  final UrlParts urlParts = extractUrlParts(url);

  if (urlParts.hostPart != baseUrlParts.hostPart) return '';

  final int max = math_lib.max(
      baseUrlParts.directories.length, urlParts.directories.length);

  for (i = 0; i < max; i++) {
    if (baseUrlParts.directories[i] != urlParts.directories[i]) break;
  }
  final List<String> baseUrlDirectories = baseUrlParts.directories.sublist(i);
  final List<String> urlDirectories = urlParts.directories.sublist(i);

  if (baseUrlDirectories.isEmpty && urlDirectories.isEmpty) {
    //both directories are the same
    return './';
  }

  urlDirectories[urlDirectories.length - 1] = ''; //join must end with '/'
  return '${"../" * (baseUrlDirectories.length - 1)}${urlDirectories.join("/")}';

//2.3.1
//abstractFileManager.prototype.pathDiff = function pathDiff(url, baseUrl) {
//    // diff between two paths to create a relative path
//
//    var urlParts = this.extractUrlParts(url),
//        baseUrlParts = this.extractUrlParts(baseUrl),
//        i, max, urlDirectories, baseUrlDirectories, diff = "";
//    if (urlParts.hostPart !== baseUrlParts.hostPart) {
//        return "";
//    }
//    max = Math.max(baseUrlParts.directories.length, urlParts.directories.length);
//    for(i = 0; i < max; i++) {
//        if (baseUrlParts.directories[i] !== urlParts.directories[i]) { break; }
//    }
//    baseUrlDirectories = baseUrlParts.directories.slice(i);
//    urlDirectories = urlParts.directories.slice(i);
//    for(i = 0; i < baseUrlDirectories.length - 1; i++) {
//        diff += "../";
//    }
//    for(i = 0; i < urlDirectories.length - 1; i++) {
//        diff += urlDirectories[i] + "/";
//    }
//    return diff;
//};
}