diff --git a/src/fsa-to-node/__tests__/util.test.ts b/src/fsa-to-node/__tests__/util.test.ts new file mode 100644 index 000000000..37d79da1b --- /dev/null +++ b/src/fsa-to-node/__tests__/util.test.ts @@ -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']); + }); +}); diff --git a/src/fsa-to-node/util.ts b/src/fsa-to-node/util.ts new file mode 100644 index 000000000..aa9688171 --- /dev/null +++ b/src/fsa-to-node/util.ts @@ -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]; +};