Skip to content

Instantly share code, notes, and snippets.

@mu-hun
Created June 4, 2023 06:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mu-hun/e531bd876c30ec103ae1e328b583ec89 to your computer and use it in GitHub Desktop.
Save mu-hun/e531bd876c30ec103ae1e328b583ec89 to your computer and use it in GitHub Desktop.
Node JS API `path.resolve` implement
export default function pathResolve(...paths: string[]) {
const parsedPaths = paths.flatMap((path) => path.split('/')).filter(Boolean);
const resolvedPaths = parsedPaths.reduce((previousValue, path) => {
if (path === '..') {
previousValue.pop();
} else {
previousValue.push(path);
}
return previousValue;
}, [] as string[]);
return resolvedPaths.join('/');
}
import { test, expect } from 'vitest';
import pathResolve from './pathResolve';
test('test pathResolve', () => {
expect(pathResolve('home/one/two', '..')).toBe('home/one');
expect(pathResolve('home/one/two', '../../')).toBe('home');
expect(pathResolve('home/one/two', 'three')).toBe('home/one/two/three');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment