From d59603f1bbdc400c2a5194bf4a720b3df17c4304 Mon Sep 17 00:00:00 2001 From: Nick Van Doorn Date: Mon, 4 Mar 2019 02:01:03 -0800 Subject: Factor out & test path helpers --- lib/path.test.ts | 11 +++++++++++ lib/path.ts | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 lib/path.test.ts diff --git a/lib/path.test.ts b/lib/path.test.ts new file mode 100644 index 0000000..af987ac --- /dev/null +++ b/lib/path.test.ts @@ -0,0 +1,11 @@ +import { getPathSuperSets } from './path' + +describe('path library', () => { + test('getPathSuperSets', () => { + expect(getPathSuperSets('/my/long/path')).toEqual([ + '/my', + '/my/long', + '/my/long/path' + ]) + }) +}) diff --git a/lib/path.ts b/lib/path.ts index ab2bb1c..df12e01 100644 --- a/lib/path.ts +++ b/lib/path.ts @@ -1,3 +1,5 @@ +import { last } from './util' + export const encodePath = (path: string): string => path .split('/') @@ -5,3 +7,34 @@ export const encodePath = (path: string): string => .join('%2F') // encode the '/' char for the url export const decodePath = (path: string): string => `/${path}` + +/** + * Split path using "/" as a delimiter + */ +export const splitPath = (path: string): string[] => + path.split('/').filter(k => k) + +/** + * Identify if a path is a root node + */ +export const isRootNode = (path: string): boolean => path === '/' || path === '' + +/** + * Check if path1 matches path2, + * if not, check if its a subpath + * + * https://stackoverflow.com/questions/37521893/determine-if-a-path-is-subdirectory-of-another-in-node-js + */ +export const isChildOrMatch = (child: string, parent: string) => { + if (child === parent || parent === '/') return true + const parentTokens = parent.split('/').filter((i: string) => i.length) + return parentTokens.every((t, i) => child.split('/')[i] === t) +} + +export const getPathSuperSets = (path: string): string[] => + splitPath(path).reduce((acc: any[], path: string) => { + if (!acc.length) return [`/${path}`] + else { + return [...acc, [last(acc), path].join('/')] + } + }, []) -- cgit v1.2.3