Last active
June 9, 2023 23:24
-
-
Save ebeloded/0aa732178c68c5b047cad9be60b1dd3f to your computer and use it in GitHub Desktop.
createPath
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type ProxyType<T> = { | |
[P in keyof T]: Record<string, ProxyType<T[P]> & Callable> & Callable | |
} | |
type Callable = { | |
(arg?: string): string | |
} | |
export function createPath<T extends {}>(_input: T): ProxyType<T> { | |
const proxy: any = (path: string[]) => | |
new Proxy(() => {}, { | |
get: (_target, prop: string) => | |
typeof path === 'symbol' ? undefined : proxy([...path, prop]), | |
apply: (_, _this, args) => { | |
const lastIndex = path.length - 1 | |
const last = path[lastIndex] /*?*/ | |
if (last === 'call') { | |
path = path.slice(0, lastIndex) | |
} else if (last === 'apply') { | |
path = path.slice(0, lastIndex) | |
args = args[1] | |
} | |
if (typeof path[path.length - 1] === 'symbol') return undefined | |
return [...path, ...args].join('/') | |
}, | |
}) | |
return proxy([]) | |
} | |
export const dbPath = createPath({ | |
workspaces: { accounts: {}, transactions: {} }, | |
}) | |
dbPath.workspaces('asdf') /*?*/ | |
dbPath.workspaces['asdf']() /*?*/ | |
dbPath.workspaces['asdf'].accounts('asdf') /*?*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment