LeetCode 71. Simplify Path

/**
 * @param {string} path
 * @return {string}
 */
var simplifyPath = function(path) {
    path = path.replace(/\/(\.(\/|$))+/g, '/').replace(/(\/)+/g, '/').replace(/\/$/, '');
    var paths = path.split('/');
    var parentCount = 0;

    for (var i = paths.length - 1; i >= 0; i--) {
        if (paths[i] === '..') {
            parentCount++;
        }

        while (parentCount && paths[i - 1] !== '..') {
            var index = i - 1;
            paths.splice(index > 0 ? index : 1, index > 0 ? 2 : 1);
            
            parentCount--;
            i--
        }
    }

    path = paths.join('/');
    return path[0] === '/' ? path : '/' + path;
};