Created
August 26, 2022 19:21
-
-
Save itelo/e03b67317bf3abcd28c5a9f8425bdce7 to your computer and use it in GitHub Desktop.
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
export const interpolatePath = ( | |
path: string, | |
variables: Record<string, string> | |
) => { | |
const reg = "[[a-zA-Z]+]"; | |
const exp = new RegExp(reg, "g"); | |
const parameters = path.match(exp); | |
const pathSpitted = path.split("/"); | |
return pathSpitted | |
.map((pathS) => { | |
if (!parameters) { | |
return pathS; | |
} | |
const index = parameters.indexOf(pathS); | |
if (index < 0) { | |
return pathS; | |
} | |
const parameterAsVariablesKey = R_prop(index, parameters).slice(1, -1); | |
const variableToInterpolateString = R_prop( | |
parameterAsVariablesKey, | |
variables | |
); | |
if (!variableToInterpolateString) { | |
throw new Error( | |
`interpolatePath Error: you forget to pass ${parameterAsVariablesKey}` | |
); | |
} | |
return variableToInterpolateString; | |
}) | |
.join("/"); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment