Last active
July 17, 2024 21:04
-
-
Save oxechicao/29281d2ba99e71fded6758609d69061e to your computer and use it in GitHub Desktop.
It works. If is the best way, I do not know. :D
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
This write from left to right | |
Patterns example: | |
+## # ## ####-#### | |
###.###.###-## | |
############## | |
(##) # ####-#### | |
*/ | |
import { useCallback } from "react"; | |
interface maskPatterProp { | |
pattern: string; | |
value: string; | |
reverse?: boolean; | |
charPattern?: string; | |
} | |
interface useMaskReturn { | |
doMask: ({}: maskPatterProp) => string; | |
} | |
const useMask = (): useMaskReturn => { | |
const doMask = useCallback( | |
({ | |
pattern, | |
value, | |
reverse = false, | |
charPattern = '#' | |
}: maskPatterProp): string => { | |
const patternArray = reverse | |
? pattern.split("").reverse() | |
: pattern.split(""); | |
const valueArray = reverse ? value.split("").reverse() : value.split(""); | |
const limitIndexPattern = patternArray.length; | |
let resultMask = ""; | |
let indexValue = 0; | |
for ( | |
let indexPattern = 0; | |
indexPattern < limitIndexPattern; | |
indexPattern++ | |
) { | |
const pat = patternArray[indexPattern]; | |
if (indexValue >= valueArray.length) { | |
break; | |
} | |
if (pat === charPattern) { | |
if (valueArray[indexValue]) { | |
resultMask = `${resultMask}${valueArray[indexValue]}`; | |
indexValue++; | |
} | |
} else { | |
resultMask = `${resultMask}${pat}`; | |
} | |
} | |
return reverse ? resultMask.split("").reverse().join("") : resultMask; | |
}, | |
[] | |
); | |
return { | |
doMask, | |
}; | |
}; | |
export default useMask; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment