Skip to content

Instantly share code, notes, and snippets.

@itelo
Created August 26, 2022 19:21
Show Gist options
  • Save itelo/e03b67317bf3abcd28c5a9f8425bdce7 to your computer and use it in GitHub Desktop.
Save itelo/e03b67317bf3abcd28c5a9f8425bdce7 to your computer and use it in GitHub Desktop.
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