Skip to content

Commit

Permalink
feat: 🎸 add pathToLocation() utility
Browse files Browse the repository at this point in the history
  • Loading branch information
streamich committed Jun 20, 2023
1 parent c8cb775 commit 8e0136a
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/fsa-to-node/__tests__/util.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { pathToLocation } from '../util';

describe('pathToLocation()', () => {
test('handles empty string', () => {
expect(pathToLocation('')).toStrictEqual([[], '']);
});

test('no path, just filename', () => {
expect(pathToLocation('scary.exe')).toStrictEqual([[], 'scary.exe']);
});

test('multiple steps in the path', () => {
expect(pathToLocation('/gg/wp/hf/gl.txt')).toStrictEqual([['gg', 'wp', 'hf'], 'gl.txt']);
expect(pathToLocation('gg/wp/hf/gl.txt')).toStrictEqual([['gg', 'wp', 'hf'], 'gl.txt']);
expect(pathToLocation('/wp/hf/gl.txt')).toStrictEqual([['wp', 'hf'], 'gl.txt']);
expect(pathToLocation('wp/hf/gl.txt')).toStrictEqual([['wp', 'hf'], 'gl.txt']);
expect(pathToLocation('/hf/gl.txt')).toStrictEqual([['hf'], 'gl.txt']);
expect(pathToLocation('hf/gl.txt')).toStrictEqual([['hf'], 'gl.txt']);
expect(pathToLocation('/gl.txt')).toStrictEqual([[], 'gl.txt']);
expect(pathToLocation('gl.txt')).toStrictEqual([[], 'gl.txt']);
});

test('handles double slashes', () => {
expect(pathToLocation('/gg/wp//hf/gl.txt')).toStrictEqual([['gg', 'wp', '', 'hf'], 'gl.txt']);
expect(pathToLocation('//gl.txt')).toStrictEqual([[''], 'gl.txt']);
});
});
11 changes: 11 additions & 0 deletions src/fsa-to-node/util.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import {FsaToNodeConstants} from "./constants";
import type {FsLocation} from "./types";

export const pathToLocation = (path: string): FsLocation => {
if (path[0] === FsaToNodeConstants.Separator) path = path.slice(1);
const lastSlashIndex = path.lastIndexOf(FsaToNodeConstants.Separator);
if (lastSlashIndex === -1) return [[], path];
const file = path.slice(lastSlashIndex + 1);
const folder = path.slice(0, lastSlashIndex).split(FsaToNodeConstants.Separator);
return [folder, file];
};

0 comments on commit 8e0136a

Please sign in to comment.