JSFiddle - React, Tailwind, and code Playground

by sdgluck

HTML

<div></div>

JavaScript

/**
 * Determine the relative path from one directory to another.
 *
 * Example:
 *
 *     let from = 'one/two/'
 *     let to = 'one/two/three/four'
 *     pathBetween(from, to) // './three/four/'
 *
 * @param {String} fromDir
 * @param {String} toDir
 * @returns {String}
 */
function pathBetween (fromDir, toDir) {
    let from = fromDir.replace(/[\/\\]+$/, '').split(path.sep);
    let to = toDir.replace(/[\/\\]+$/, '').split(path.sep);
    let len = Math.max(from.length, to.length);

    let numSame = 0;
    let differentStart = 0;

    for (let i = 0; i < len; i++) {
        if (from[i] === to[i]) {
            numSame++;
        } else {
            differentStart = i;
            break;
        }
    }

    let upDirs = new Array(from.length - differentStart).fill('..');
    let namedDirs = to.slice(numSame, to.length);

    return upDirs.concat(namedDirs).join('/') + '/';
}