locutus
Version:
Locutus other languages' standard libraries to JavaScript for fun and educational purposes
51 lines (50 loc) • 1.49 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Join = Join;
const cleanPath = (path) => {
if (path === '') {
return '.';
}
const rooted = path.startsWith('/');
const segments = path.split('/');
const stack = [];
for (const segment of segments) {
if (segment === '' || segment === '.') {
continue;
}
if (segment === '..') {
const top = stack.at(-1);
if (top && top !== '..') {
stack.pop();
}
else if (!rooted) {
stack.push('..');
}
continue;
}
stack.push(segment);
}
const cleaned = `${rooted ? '/' : ''}${stack.join('/')}`;
if (cleaned === '') {
return rooted ? '/' : '.';
}
return cleaned;
};
function Join(...elem) {
// discuss at: https://locutus.io/golang/path/Join
// parity verified: Go 1.23
// original by: Kevin van Zonneveld (https://kvz.io)
// example 1: Join('a', 'b', 'c')
// returns 1: 'a/b/c'
// example 2: Join('/a/', '/b/', 'c')
// returns 2: '/a/b/c'
// example 3: Join('a', '..', 'b')
// returns 3: 'b'
// example 4: Join('', '')
// returns 4: ''
const parts = elem.map((value) => String(value));
if (parts.every((value) => value === '')) {
return '';
}
return cleanPath(parts.join('/'));
}