MCPcopy Create free account
hub / github.com/denoland/std / normalizeString

Function normalizeString

path/_common/normalize_string.ts:9–74  ·  view source on GitHub ↗
(
  path: string,
  allowAboveRoot: boolean,
  separator: string,
  isPathSeparator: (code: number) => boolean,
)

Source from the content-addressed store, hash-verified

7
8// Resolves . and .. elements in a path with directory names
9export function normalizeString(
10 path: string,
11 allowAboveRoot: boolean,
12 separator: string,
13 isPathSeparator: (code: number) => boolean,
14): string {
15 let res = "";
16 let lastSegmentLength = 0;
17 let lastSlash = -1;
18 let dots = 0;
19 let code: number | undefined;
20 for (let i = 0; i <= path.length; ++i) {
21 if (i < path.length) code = path.charCodeAt(i);
22 else if (isPathSeparator(code!)) break;
23 else code = CHAR_FORWARD_SLASH;
24
25 if (isPathSeparator(code!)) {
26 if (lastSlash === i - 1 || dots === 1) {
27 // NOOP
28 } else if (lastSlash !== i - 1 && dots === 2) {
29 if (
30 res.length < 2 ||
31 lastSegmentLength !== 2 ||
32 res.charCodeAt(res.length - 1) !== CHAR_DOT ||
33 res.charCodeAt(res.length - 2) !== CHAR_DOT
34 ) {
35 if (res.length > 2) {
36 const lastSlashIndex = res.lastIndexOf(separator);
37 if (lastSlashIndex === -1) {
38 res = "";
39 lastSegmentLength = 0;
40 } else {
41 res = res.slice(0, lastSlashIndex);
42 lastSegmentLength = res.length - 1 - res.lastIndexOf(separator);
43 }
44 lastSlash = i;
45 dots = 0;
46 continue;
47 } else if (res.length === 2 || res.length === 1) {
48 res = "";
49 lastSegmentLength = 0;
50 lastSlash = i;
51 dots = 0;
52 continue;
53 }
54 }
55 if (allowAboveRoot) {
56 if (res.length > 0) res += `${separator}..`;
57 else res = "..";
58 lastSegmentLength = 2;
59 }
60 } else {
61 if (res.length > 0) res += separator + path.slice(lastSlash + 1, i);
62 else res = path.slice(lastSlash + 1, i);
63 lastSegmentLength = i - lastSlash - 1;
64 }
65 lastSlash = i;
66 dots = 0;

Callers 5

normalizeFunction · 0.90
resolveFunction · 0.90
normalizeFunction · 0.90
resolveFunction · 0.90

Calls 2

isPathSeparatorFunction · 0.85
sliceMethod · 0.45

Tested by

no test coverage detected