added processString util

This commit is contained in:
srgooglo 2022-06-03 21:13:19 +02:00
parent f04b4994d6
commit 8a6335762d
2 changed files with 44 additions and 1 deletions

View File

@ -2,4 +2,5 @@ export { default as useLongPress } from "./useLongPress"
export { default as findChildById } from "./findChildById" export { default as findChildById } from "./findChildById"
export { default as cursorPosition } from "./cursorPosition" export { default as cursorPosition } from "./cursorPosition"
export { default as getBase64 } from "./getBase64" export { default as getBase64 } from "./getBase64"
export { default as Haptics } from "./haptics" export { default as Haptics } from "./haptics"
export { default as processString } from "./processString"

View File

@ -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
}
}