As part of our string processing task, we are looking to apply formatting to text enclosed within '*' and '**' with <strong></strong>
, and text surrounded by backticks with <code> </code>
. I've implemented a logic that achieves this functionality flawlessly. However, the code seems overly complex for such a simple task. Below is the current implementation. Any suggestions for improvement would be greatly appreciated.
input =
"*within single star* and **within double start** and this is `backtick string`"
output =
"<strong>within single star</strong> and <strong>within double start</strong> and this is <code>backtick string</code>"
transform(data: any) {
if (data) {
const processDblStar = (input) => {
const regExforDoubleStar = /(\*\*)+/gi;
let i = 0;
const result = input.replace(regExforDoubleStar, (match, matchedStr, offset) => {
i++;
return i % 2 === 0 ? '</strong>' : '<strong>';
});
return result;
};
const processSingleStar = (input) => {
const regExforSingleStar = /(\*)+/gi;
let i = 0;
const result = input.replace(regExforSingleStar, (match, matchedStr, offset) => {
i++;
return i % 2 === 0 ? '</strong>' : '<strong>';
});
return result;
};
const processBackTick = (input) => {
const regExforBackTick = /(\`)+/gi;
let i = 0;
const result = input.replace(regExforBackTick, (match, matchedStr, offset) => {
i++;
return i % 2 === 0 ? '</code>' : '<code>';
});
return result;
};
const processPipeline = (functions) => (inputStr) => functions.reduce((result, fn) => fn(result), inputStr);
const funcArr: Function[] = [];
if (data.indexOf('`') >= 0) {
funcArr.push(processBackTick);
}
if (data.indexOf('*') >= 0) {
funcArr.push(processSingleStar);
}
if (data.indexOf('**') >= 0) {
funcArr.push(processDblStar);
}
processPipeline(funcArr)(data);
}
}