Debian Codegraph @

path2/_normalize-array.js

raw
1 // resolves . and .. elements in a path array with directory names there
2 // must be no slashes, empty elements, or device names (c:\) in the array
3 // (so also no leading and trailing slashes - it does not distinguish
4 // relative and absolute paths)
5
6 'use strict';
7
8 module.exports = function normalizeArray(parts, allowAboveRoot) {
9 // if the path tries to go above the root, `up` ends up > 0
10 var up = 0, i, last;
11 for (i = parts.length - 1; i >= 0; i--) {
12 last = parts[i];
13 if (last === '.') {
14 parts.splice(i, 1);
15 } else if (last === '..') {
16 parts.splice(i, 1);
17 up++;
18 } else if (up) {
19 parts.splice(i, 1);
20 up--;
21 }
22 }
23
24 // if the path is allowed to go above the root, restore leading ..s
25 if (allowAboveRoot) {
26 for (up; up--; up) {
27 parts.unshift('..');
28 }
29 }
30
31 return parts;
32 };