UNPKG

locutus

Version:

Locutus other languages' standard libraries to JavaScript for fun and educational purposes

48 lines (47 loc) 1.4 kB
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; }; export 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('/')); }