relative_url.js 944 B

123456789101112131415161718192021222324252627282930313233343536
  1. 'use strict';
  2. const encodeURL = require('./encode_url');
  3. const Cache = require('./cache');
  4. const cache = new Cache();
  5. function relativeUrlHelper(from = '', to = '') {
  6. return cache.apply(`${from}-${to}`, () => {
  7. const fromParts = from.split('/');
  8. const toParts = to.split('/');
  9. const length = Math.min(fromParts.length, toParts.length);
  10. let i = 0;
  11. for (; i < length; i++) {
  12. if (fromParts[i] !== toParts[i]) break;
  13. }
  14. let out = toParts.slice(i);
  15. for (let j = fromParts.length - i - 1; j > 0; j--) {
  16. out.unshift('..');
  17. }
  18. const outLength = out.length;
  19. // If the last 2 elements of `out` is empty strings, replace them with `index.html`.
  20. if (outLength > 1 && !out[outLength - 1] && !out[outLength - 2]) {
  21. out = out.slice(0, outLength - 2).concat('index.html');
  22. }
  23. return encodeURL(out.join('/').replace(/\/{2,}/g, '/'));
  24. });
  25. }
  26. module.exports = relativeUrlHelper;