Skip to content

Commit 91dd3ec

Browse files
committed
CCM-11438 Fix interpolate tests
1 parent 5bfaf45 commit 91dd3ec

File tree

1 file changed

+12
-11
lines changed

1 file changed

+12
-11
lines changed

frontend/src/utils/interpolate.ts

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@
1212
* count: 2,
1313
* });
1414
* // => 'Hello John, you have 2 messages.'
15-
* * interpolate('Hello {{name}}, you have {{count}} {{count|message|messages}}.', {
15+
*
16+
* interpolate('Hello {{name}}, you have {{count}} {{count|message|messages}}.', {
1617
* name: 'John',
1718
* count: 1,
1819
* });
@@ -23,26 +24,26 @@
2324
* @param variables - An object of variables
2425
* @returns The interpolated string
2526
*/
26-
// the following regex is bounded, avoids nested repetition, and is safe for controlled templates
27+
2728
// eslint-disable-next-line security/detect-unsafe-regex, sonarjs/slow-regex
28-
const interpolationPattern = /{{\s*(\w+)(?:\|([^|]+)\|([^|]+))?\s*}}/g;
29+
const interpolationPattern = /{{\s*([^}|]+)(?:\|([^}|]+)\|([^}]+))?\s*}}/g;
2930

3031
export function interpolate(
3132
template: string,
3233
variables: Record<string, string | number> = {}
3334
): string {
3435
// eslint-disable-next-line unicorn/prefer-string-replace-all
35-
return template.replace(interpolationPattern, (_, token) => {
36-
const parts = token.split('|').map((part: string) => part.trim());
36+
return template.replace(interpolationPattern, (_match, variable, singular, plural) => {
37+
const key = variable.trim();
38+
const value = variables[key];
39+
40+
if (singular !== undefined && plural !== undefined) {
41+
const count = Number(value);
3742

38-
if (parts.length === 3) {
39-
const [variable, singular, plural] = parts;
40-
const value = Number(variables[variable]);
41-
if (Number.isNaN(value)) return plural;
42-
return value === 1 ? singular : plural;
43+
if (Number.isNaN(count)) return plural;
44+
return count === 1 ? singular : plural;
4345
}
4446

45-
const value = variables[parts[0]];
4647
return value == null ? '' : String(value);
4748
});
4849
}

0 commit comments

Comments
 (0)