Last active
October 16, 2018 21:54
-
-
Save moshmage/999f38d8a1c2e605002a7d37e9b59ee8 to your computer and use it in GitHub Desktop.
masking a string
This file contains hidden or 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
/** | |
* Replaces value inside {value} with a spaced representation of the masked array | |
* and then replaces the Nth caret with the provided key, returning the new masked | |
* value. | |
* @param {(RegExp | string)[]} mask | |
* @param {string} key | |
* @param {number} caretPos | |
* @param {string} value | |
* @returns <{str: string, pos: number}> | |
*/ | |
maskValue(mask: (RegExp|string)[], key: string, caretPos: number, value?: string) { | |
if (caretPos < 0 || caretPos > mask.length || value.length > mask.length) return {str: value, pos: 0}; | |
if (!value) value = mask.map(k => k instanceof RegExp ? '0' : k).join(''); | |
const returnValue = (str: string, pos: number) => { return {str, pos}; }; | |
if (!key) return returnValue(value, 0); | |
if (!(mask[caretPos] instanceof RegExp) && (mask[caretPos + 1] && (<RegExp>mask[caretPos + 1]).test(key))) | |
return returnValue(value.substr(0, caretPos) + mask[caretPos] + key + value.substr(caretPos + 2), caretPos + 2); | |
if ((mask[caretPos] instanceof RegExp && !(<RegExp>mask[caretPos]).test(key)) || | |
(!(mask[caretPos] instanceof RegExp) && mask[caretPos] !== key)) | |
return returnValue(value.substr(0, caretPos), caretPos); | |
return returnValue(value.substr(0, caretPos) + key + value.substr(caretPos + 1), caretPos + 1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment