GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — path: refactor for performance and consistency by nwoltman · Pull Request #1778 · nodejs/node

path: refactor for performance and consistency #1778

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Sign up for GitHub

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
nwoltman wants to merge 2 commits into nodejs:master from nwoltman:path

Uh oh!

There was an error while loading. Please reload this page.

Closed

path: refactor for performance and consistency #1778

Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit Hold shift + click to select a range
84e4f5b
path: refactor for performance and consistency
nwoltman May 23, 2015
363335c
benchmark: Add some path benchmarks for #1778
nwoltman Jun 6, 2015
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view
Next Next commit
path: refactor for performance and consistency
Improve performance by:
+ Not leaking the `arguments` object!
+ Getting the last character of a string by index, instead of
  with `.substr()` or `.slice()`

Improve code consistency by:
+ Using `[]` instead of `.charAt()` where possible
+ Using a function declaration instead of a var declaration
+ Using `.slice()` with clearer arguments
+ Checking if `dir` is truthy in `win32.format`
  (added tests for this)

Improve both by:
+ Making the reusable `trimArray()` function
+ Standardizing getting certain path statistics with
  the new `win32StatPath()` function
  • Loading branch information

Uh oh!

There was an error while loading. Please reload this page.

@nwoltman
nwoltman committed Jul 3, 2015
commit 84e4f5b75408790bbf43b1260ace11eb0485b7f6

There are no files selected for viewing

139 changes: 69 additions & 70 deletions 139 lib/path.js
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,29 @@ function normalizeArray(parts, allowAboveRoot) {
return res;
}

// Returns an array with empty elements removed from either end of the input
// array or the original array if no elements need to be removed
Comment thread

@thefourtheye thefourtheye Jun 17, 2015

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not sure if returning the original array and a new array based on conditions is a good idea.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

@nwoltman nwoltman Jun 17, 2015

Copy link
Copy Markdown
Contributor Author

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's just a little helper function. There's no point in making a copy of an array when the original is all you need.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
function trimArray(arr) {
var lastIndex = arr.length - 1;
var start = 0;
for (; start <= lastIndex; start++) {
if (arr[start])
break;
}

var end = lastIndex;
for (; end >= 0; end--) {
if (arr[end])
break;
}

if (start === 0 && end === lastIndex)
return arr;
if (start > end)
return [];
return arr.slice(start, end + 1);
}

// Regex to split a windows path into three parts: [*, device, slash,
// tail] windows-only
const splitDeviceRe =
Expand All @@ -62,9 +85,21 @@ function win32SplitPath(filename) {
return [device, dir, basename, ext];
}

var normalizeUNCRoot = function(device) {
function win32StatPath(path) {
var result = splitDeviceRe.exec(path),
device = result[1] || '',
isUnc = !!device && device[1] !== ':';
return {
device,
isUnc,
isAbsolute: isUnc || !!result[2], // UNC paths are always absolute
tail: result[3]
};
}

function normalizeUNCRoot(device) {
return '\\\\' + device.replace(/^[\\\/]+/, '').replace(/[\\\/]+/g, '\\');
};
}

// path.resolve([from ...], to)
win32.resolve = function() {
Expand Down Expand Up @@ -99,11 +134,11 @@ win32.resolve = function() {
continue;
}

var result = splitDeviceRe.exec(path),
device = result[1] || '',
isUnc = device && device.charAt(1) !== ':',
isAbsolute = win32.isAbsolute(path),
tail = result[3];
var result = win32StatPath(path),
device = result.device,
isUnc = result.isUnc,
isAbsolute = result.isAbsolute,
tail = result.tail;

if (device &&
resolvedDevice &&
Expand Down Expand Up @@ -147,11 +182,11 @@ win32.resolve = function() {
win32.normalize = function(path) {
assertPath(path);

var result = splitDeviceRe.exec(path),
device = result[1] || '',
isUnc = device && device.charAt(1) !== ':',
isAbsolute = win32.isAbsolute(path),
tail = result[3],
var result = win32StatPath(path),
device = result.device,
isUnc = result.isUnc,
isAbsolute = result.isAbsolute,
tail = result.tail,
trailingSlash = /[\\\/]$/.test(tail);

// Normalize the tail path
Expand All @@ -176,23 +211,19 @@ win32.normalize = function(path) {

win32.isAbsolute = function(path) {
assertPath(path);

var result = splitDeviceRe.exec(path),
device = result[1] || '',
isUnc = !!device && device.charAt(1) !== ':';
// UNC paths are always absolute
return !!result[2] || isUnc;
return win32StatPath(path).isAbsolute;
};

win32.join = function() {
function f(p) {
if (typeof p !== 'string') {
throw new TypeError('Arguments to path.join must be strings');
var paths = [];
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
assertPath(arg);
if (arg) {
paths.push(arg);
}
return p;
}

var paths = Array.prototype.filter.call(arguments, f);
var joined = paths.join('\\');

// Make sure that the joined path doesn't start with two slashes, because
Expand Down Expand Up @@ -232,25 +263,10 @@ win32.relative = function(from, to) {
var lowerFrom = from.toLowerCase();
var lowerTo = to.toLowerCase();

function trim(arr) {
var start = 0;
for (; start < arr.length; start++) {
if (arr[start] !== '') break;
}

var end = arr.length - 1;
for (; end >= 0; end--) {
if (arr[end] !== '') break;
}

if (start > end) return [];
return arr.slice(start, end + 1);
}
var toParts = trimArray(to.split('\\'));

var toParts = trim(to.split('\\'));

var lowerFromParts = trim(lowerFrom.split('\\'));
var lowerToParts = trim(lowerTo.split('\\'));
var lowerFromParts = trimArray(lowerFrom.split('\\'));
var lowerToParts = trimArray(lowerTo.split('\\'));

var length = Math.min(lowerFromParts.length, lowerToParts.length);
var samePartsLength = length;
Expand Down Expand Up @@ -356,15 +372,13 @@ win32.format = function(pathObject) {

var dir = pathObject.dir;
var base = pathObject.base || '';
if (dir.slice(dir.length - 1, dir.length) === win32.sep) {
return dir + base;
if (!dir) {
return base;
}

if (dir) {
return dir + win32.sep + base;
if (dir[dir.length - 1] === win32.sep) {
return dir + base;
}

return base;
return dir + win32.sep + base;
};


Expand All @@ -377,7 +391,7 @@ win32.parse = function(pathString) {
}
return {
root: allParts[0],
dir: allParts[0] + allParts[1].slice(0, allParts[1].length - 1),
dir: allParts[0] + allParts[1].slice(0, -1),
base: allParts[2],
ext: allParts[3],
name: allParts[2].slice(0, allParts[2].length - allParts[3].length)
Expand Down Expand Up @@ -418,7 +432,7 @@ posix.resolve = function() {
}

resolvedPath = path + '/' + resolvedPath;
resolvedAbsolute = path.charAt(0) === '/';
resolvedAbsolute = path[0] === '/';
}

// At this point the path should be resolved to a full absolute path, but
Expand All @@ -437,7 +451,7 @@ posix.normalize = function(path) {
assertPath(path);

var isAbsolute = posix.isAbsolute(path),
trailingSlash = path.substr(-1) === '/';
trailingSlash = path && path[path.length - 1] === '/';

// Normalize the path
path = normalizeArray(path.split('/'), !isAbsolute).join('/');
Expand All @@ -455,7 +469,7 @@ posix.normalize = function(path) {
// posix version
posix.isAbsolute = function(path) {
assertPath(path);
return path.charAt(0) === '/';
return !!path && path[0] === '/';
};

// posix version
Expand Down Expand Up @@ -487,23 +501,8 @@ posix.relative = function(from, to) {
from = posix.resolve(from).substr(1);
to = posix.resolve(to).substr(1);

function trim(arr) {
var start = 0;
for (; start < arr.length; start++) {
if (arr[start] !== '') break;
}

var end = arr.length - 1;
for (; end >= 0; end--) {
if (arr[end] !== '') break;
}

if (start > end) return [];
return arr.slice(start, end + 1);
}

var fromParts = trim(from.split('/'));
var toParts = trim(to.split('/'));
var fromParts = trimArray(from.split('/'));
var toParts = trimArray(to.split('/'));

var length = Math.min(fromParts.length, toParts.length);
var samePartsLength = length;
Expand Down Expand Up @@ -602,7 +601,7 @@ posix.parse = function(pathString) {

return {
root: allParts[0],
dir: allParts[0] + allParts[1].slice(0, allParts[1].length - 1),
dir: allParts[0] + allParts[1].slice(0, -1),
base: allParts[2],
ext: allParts[3],
name: allParts[2].slice(0, allParts[2].length - allParts[3].length)
Expand Down
26 changes: 22 additions & 4 deletions 26 test/parallel/test-path-parse-format.js
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,12 @@ var winPaths = [
'\\\\server two\\shared folder\\file path.zip',
'\\\\teela\\admin$\\system32',
'\\\\?\\UNC\\server\\share'
];

var winSpecialCaseFormatTests = [
[{dir: 'some\\dir'}, 'some\\dir\\'],
[{base: 'index.html'}, 'index.html'],
[{}, '']
];

var unixPaths = [
Expand All @@ -30,6 +35,12 @@ var unixPaths = [
'C:\\foo'
];

var unixSpecialCaseFormatTests = [
[{dir: 'some/dir'}, 'some/dir/'],
[{base: 'index.html'}, 'index.html'],
[{}, '']
];

var errors = [
{method: 'parse', input: [null],
message: /Path must be a string. Received null/},
Expand Down Expand Up @@ -57,10 +68,12 @@ var errors = [
message: /'pathObject.root' must be a string or undefined, not number/},
];

check(path.win32, winPaths);
check(path.posix, unixPaths);
checkParseFormat(path.win32, winPaths);
checkParseFormat(path.posix, unixPaths);
checkErrors(path.win32);
checkErrors(path.posix);
checkFormat(path.win32, winSpecialCaseFormatTests);
checkFormat(path.posix, unixSpecialCaseFormatTests);

function checkErrors(path) {
errors.forEach(function(errorCase) {
Expand All @@ -79,8 +92,7 @@ function checkErrors(path) {
});
}


function check(path, paths) {
function checkParseFormat(path, paths) {
paths.forEach(function(element, index, array) {
var output = path.parse(element);
assert.strictEqual(path.format(output), element);
Expand All @@ -89,3 +101,9 @@ function check(path, paths) {
assert.strictEqual(output.ext, path.extname(element));
});
}

function checkFormat(path, testCases) {
testCases.forEach(function(testCase) {
assert.strictEqual(path.format(testCase[0]), testCase[1]);
});
}
Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.