Skip to content

Commit 1f578a8

Browse files
committed
add basic recursive variable replacer
1 parent 751d6e9 commit 1f578a8

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

src/helpers/variable-replacer.ts

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import { isJSONEncodable } from 'discord.js';
2+
3+
export function replaceVariables<T>(
4+
variableMap: Record<string, unknown>,
5+
obj: T
6+
): T {
7+
if (typeof obj === 'string') {
8+
return replaceVariablesInString(variableMap, obj) as unknown as T;
9+
}
10+
11+
if (Array.isArray(obj)) {
12+
return obj.map((item) =>
13+
replaceVariables(variableMap, item)
14+
) as unknown as T;
15+
}
16+
17+
if (typeof obj === 'object') {
18+
const newObj = isJSONEncodable(obj) ? (obj.toJSON() as T) : { ...obj };
19+
for (const key in newObj) {
20+
newObj[key] = replaceVariables(variableMap, newObj[key]);
21+
}
22+
return newObj;
23+
}
24+
25+
return obj;
26+
}
27+
28+
export function replaceVariablesInString(
29+
variables: Record<string, unknown>,
30+
str: string
31+
): string {
32+
Object.entries(variables).forEach(([key, value]) => {
33+
str = str.replaceAll(key, value?.toString());
34+
});
35+
return str;
36+
}

0 commit comments

Comments
 (0)