diff --git a/src/path.ts b/src/path.ts index b902001..3de767c 100644 --- a/src/path.ts +++ b/src/path.ts @@ -71,26 +71,28 @@ export const normalize: typeof path.normalize = function (path: string) { return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path; }; -export const join: typeof path.join = function (...arguments_) { - if (arguments_.length === 0) { - return "."; - } +export const join: typeof path.join = function (...segments) { + let path = ""; - let joined: string; - for (const argument of arguments_) { - if (argument && argument.length > 0) { - if (joined === undefined) { - joined = argument; + for (const seg of segments) { + if (!seg) { + continue; + } + if (path.length > 0) { + const pathTrailing = path[path.length - 1] === "/"; + const segLeading = seg[0] === "/"; + const both = pathTrailing && segLeading; + if (both) { + path += seg.slice(1); } else { - joined += `/${argument}`; + path += pathTrailing || segLeading ? seg : `/${seg}`; } + } else { + path += seg; } } - if (joined === undefined) { - return "."; - } - return normalize(joined.replace(/\/\/+/g, "/")); + return normalize(path); }; function cwd() { diff --git a/test/index.spec.ts b/test/index.spec.ts index 49c112d..269c911 100644 --- a/test/index.spec.ts +++ b/test/index.spec.ts @@ -160,6 +160,10 @@ runTest("format", format, [ runTest("join", join, [ ["."], [undefined, "."], + ["", "."], + ["./", "./"], + ["", "/foo", "/foo"], + ["/foo", "//bar", "/foo/bar"], ["/", "/path", "/path"], ["/test//", "//path", "/test/path"], ["some/nodejs/deep", "../path", "some/nodejs/path"], @@ -187,6 +191,7 @@ runTest("join", join, [ [String.raw`\\server\share\file`, String.raw`..\path`, "//server/share/path"], [String.raw`\\.\c:\temp\file`, String.raw`..\path`, "//./c:/temp/path"], [String.raw`\\server/share/file`, "../path", "//server/share/path"], + [String.raw`//server/share/file`, "../path", "//server/share/path"], ]); runTest("normalize", normalize, {