relative_url.js 741 B

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