import { PATH_SEPARATOR } from "./PATH_SEPARATOR.js";

/**
 * Returns the directory name of a path, similar to the Unix dirname command.
 * @param {string} path
 * @return {string}
 */
export function computePathDirectory(path) {
    if (typeof path !== "string") {
        throw new Error('path is not a string');
    }

    let lastSlashIndex = path.lastIndexOf(PATH_SEPARATOR);

    //rewind in case of trailing slashes
    while (lastSlashIndex > 0 && path.charAt(lastSlashIndex - 1) === PATH_SEPARATOR) {
        lastSlashIndex--;
    }

    if (lastSlashIndex !== -1) {
        return path.substring(0, lastSlashIndex);
    } else {
        return path;
    }
}
