Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions packages/common/src/constants/regexp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,20 @@ export const SLOT_ANNOTATION_SIMPLE_REGEX = /{([^ .[\]{}]+?)}/g;

export const IS_VARIABLE_REGEXP = /^{.*}$/;

// export const READABLE_VARIABLE_REGEXP = /{(\w{1,64})}/g;
export const READABLE_VARIABLE_REGEXP = /{(\w{1,64})((?:\.\w{1,64}|\[\d+])*)}/gi;
/**
* Matches:
* {var}
* {var.x}
* {var.x.y}
* {var.x.y[0]}
* {var.x.y[other]}
* {var[0]}
* {var[other]}
* {var[0].x}
* {var[other].y}
* ... etc
*/
export const READABLE_VARIABLE_REGEXP = /{(\w{1,64})((?:\.\w{1,64}|\[\d]|\[\w{1,64}])*)}/gi;

export const VALID_CHARACTER = 'a-zA-Z';

Expand Down
19 changes: 19 additions & 0 deletions packages/common/src/utils/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,22 @@ export const removeTrailingUnderscores = (str: string): string => str.replace(TR
export const conditionalReplace = (base: string, pattern: RegExp, value?: string) => {
return value ? base.replace(pattern, value) : base;
};

/**
* Recursively call String.prototype.replace until the result is unchanged.
* This is more useful when the `replacer` may end up returning something that should be replaced.
*
* For simple "recursive" replacements use the global RegExp flag (`g`) and not this method.
*/
export const recursiveReplace = (
str: string,
searchValue: string | RegExp,
replacer: (substring: string, ...args: any[]) => string,
maxDepth = Infinity,
currentDepth = 0
): string => {
const replacedString = str.replace(searchValue, replacer);
if (replacedString === str) return replacedString;
if (currentDepth >= maxDepth) return replacedString;
return recursiveReplace(replacedString, searchValue, replacer, maxDepth, currentDepth + 1);
};
64 changes: 29 additions & 35 deletions packages/common/src/utils/variables.ts
Original file line number Diff line number Diff line change
@@ -1,53 +1,47 @@
import { READABLE_VARIABLE_REGEXP } from '@common/constants';
import { hasProperty } from '@common/utils/object';
import { recursiveReplace } from '@common/utils/string';
import { get } from 'lodash';

const resolveVariableSelectorPath = (variableValue: unknown, trimmedSelectorPath: string, defaultValue?: string) => {
if (trimmedSelectorPath) {
return typeof variableValue === 'object' ? get(variableValue, trimmedSelectorPath, defaultValue) : defaultValue;
}
return variableValue;
};

export const variableReplacer = (
match: string,
inner: string,
selectors: string[],
matchedString: string,
variableName: string,
selectorPath: string,
variables: Record<string, unknown>,
modifier?: (variable: unknown) => unknown
): unknown => {
if (!(inner in variables)) {
return match;
}
if (!hasProperty(variables, variableName)) return matchedString;

let replaced: any = variables[inner];

let selectorString = selectors[0];
while (selectorString.length > 0) {
// eslint-disable-next-line no-loop-func
selectorString = selectorString.replace(/^\.(\w{1,64})/, (_m, field) => {
replaced = replaced[field];
return '';
});
if (replaced === undefined) {
break;
}
// eslint-disable-next-line no-loop-func
selectorString = selectorString.replace(/^\[(\d+)]/, (_m, index) => {
replaced = replaced[index];
return '';
});
if (replaced === undefined) {
break;
}
}
const variableValue = variables[variableName];
const trimmedSelectorPath = selectorPath.startsWith('.') ? selectorPath.substring(1) : selectorPath;

const resolvedValue = resolveVariableSelectorPath(variableValue, trimmedSelectorPath, matchedString);

return typeof modifier === 'function' ? modifier(replaced) : replaced;
return typeof modifier === 'function' ? modifier(resolvedValue) : resolvedValue;
};

export const replaceVariables = (
phrase: string | undefined | null,
variables: Record<string, unknown>,
modifier: ((variable: unknown) => unknown) | undefined = undefined,
modifier?: (variable: unknown) => unknown,
{ trim = true }: { trim?: boolean } = {}
): string => {
if (!phrase || (trim && !phrase.trim())) {
return '';
}

return phrase.replace(READABLE_VARIABLE_REGEXP, (match, inner, ...selectors) =>
String(variableReplacer(match, inner, selectors, variables, modifier))
const trimmedPhrase = trim ? phrase?.trim() : phrase;
if (!trimmedPhrase) return '';

return recursiveReplace(
trimmedPhrase,
READABLE_VARIABLE_REGEXP,
(matchedString, variableName: string, selectorPath: string) =>
String(variableReplacer(matchedString, variableName, selectorPath, variables, modifier)),
10
);
};

Expand Down
14 changes: 14 additions & 0 deletions packages/common/tests/utils/string.unit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { recursiveReplace } from '@common/utils/string';
import { expect } from 'chai';

describe('Utils | string', () => {
describe('recursiveReplace', () => {
it('replaces until it cannot replace any more', () => {
// act
const result = recursiveReplace('heeeeeeello', 'ee', () => 'e');

// assert
expect(result).to.equal('hello');
});
});
});
Loading