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 Sim0000
"use strict";
function simplifyPath(path) {
let result = path[0] == '/' ? [''] : [];
for(let d of path.split('/')){
if(d == '.' || d == '') continue;
if(result.length == 0 || d != '..' || result[result.length - 1] == '..'){
result.push(d);
} else if(d == '..' && result[result.length - 1] != ''){
result.pop();
}
}
return result.join('/') || (result.length ? '/' : '.');
}
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. 2, 2017