summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorNick Van Doorn <vandoorn.nick@gmail.com>2019-03-04 02:01:03 -0800
committerNick Van Doorn <vandoorn.nick@gmail.com>2019-03-04 02:01:03 -0800
commitd59603f1bbdc400c2a5194bf4a720b3df17c4304 (patch)
treed32245ebe1beb804eec4edca616f61b377902daa
parentafb0dc84bd87592e36768c3800588311a4705b46 (diff)
Factor out & test path helpers
-rw-r--r--lib/path.test.ts11
-rw-r--r--lib/path.ts33
2 files changed, 44 insertions, 0 deletions
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('/')]
+ }
+ }, [])