Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for [old] Simplify Unix Path by mortonfox
"use strict";
function simplifyPath(path) {
// simplifying a given path
let abs_path = path.startsWith('/');
let newparts = [];
for (let part of path.split('/')) {
if (part === '' || part === '.') {
continue;
}
if (part === '..') {
if (newparts.length && newparts[newparts.length - 1] !== '..') {
newparts.pop();
continue;
}
if (!newparts.length && abs_path) {
continue; // Already at root - swallow the double dot.
}
// Relative path and can't go up - keep the double dot.
}
newparts.push(part);
}
// If it is a relative path and there aren't any components, we need at least a single dot.
return (abs_path ? '/' : (newparts.length ? '' : '.')) + newparts.join('/');
}
var assert = require('assert');
if (!global.is_checking) {
// last slash is not important
assert.equal(simplifyPath('/a/'), '/a')
// double slash can be united in one
assert.equal(simplifyPath('/a//b/c'), '/a/b/c')
// double dot - go to previous folder
assert.equal(simplifyPath('dir/fol/../no'), 'dir/no')
assert.equal(simplifyPath('dir/fol/../../no'), 'no')
// one dot means current dir
assert.equal(simplifyPath('/a/b/./ci'), '/a/b/ci')
assert.equal(simplifyPath('vi/..'), '.')
assert.equal(simplifyPath('./.'), '.')
// you can't go deeper than root folder
assert.equal(simplifyPath('/for/../..'), '/')
assert.equal(simplifyPath('/for/../../no/..'), '/')
// not all double-dots can be simplyfied in related path
assert.equal(simplifyPath('for/../..'), '..')
assert.equal(simplifyPath('../foo'), '../foo')
console.log("Coding complete? Click 'Check' to review your tests and earn cool rewards!");
}
Aug. 1, 2017