diff --git a/packages/app/src/utils/index.js b/packages/app/src/utils/index.js index 84ddf0ab..9516229b 100644 --- a/packages/app/src/utils/index.js +++ b/packages/app/src/utils/index.js @@ -2,4 +2,5 @@ export { default as useLongPress } from "./useLongPress" export { default as findChildById } from "./findChildById" export { default as cursorPosition } from "./cursorPosition" export { default as getBase64 } from "./getBase64" -export { default as Haptics } from "./haptics" \ No newline at end of file +export { default as Haptics } from "./haptics" +export { default as processString } from "./processString" \ No newline at end of file diff --git a/packages/app/src/utils/processString/index.js b/packages/app/src/utils/processString/index.js new file mode 100644 index 00000000..a7b802f5 --- /dev/null +++ b/packages/app/src/utils/processString/index.js @@ -0,0 +1,42 @@ +export default function processString(options) { + let key = 0 + + function processInputWithRegex(option, input) { + if (!option.fn || typeof option.fn !== "function") + return input + + if (!option.regex || !(option.regex instanceof RegExp)) + return input + + if (typeof input === "string") { + let regex = option.regex + let result = null + let output = [] + + while ((result = regex.exec(input)) !== null) { + let index = result.index + let match = result[0] + + output.push(input.substring(0, index)) + output.push(option.fn(++key, result)) + + input = input.substring(index + match.length, input.length + 1) + regex.lastIndex = 0 + } + + output.push(input) + return output + } else if (Array.isArray(input)) { + return input.map(chunk => processInputWithRegex(option, chunk)) + } else return input + } + + return function (input) { + if (!options || !Array.isArray(options) || !options.length) + return input + + options.forEach(option => input = processInputWithRegex(option, input)) + + return input + } +} \ No newline at end of file