Last active
July 15, 2016 09:14
-
-
Save dhoko/fc5eba7a2d382327157e to your computer and use it in GitHub Desktop.
Apply a mask to a String
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
/** | |
* Format an input from a given mask, key per key | |
* - XXXX-XXX-XXX-XXX => 1111-222-333-444 | |
* - XXXX XXXX XXXX => 1111 2222 3333 | |
* - XX/XX => 11/22 | |
* @param {String} mask | |
* @return {Function} | |
*/ | |
const maskInput = (mask = '') => { | |
const maskLength = mask.length; | |
const maskSepators = mask.match(/[^X]/g); | |
let maskReplaced = ''; | |
let i = 0; | |
/** | |
* Input string to format following the mask | |
* @param {String} input | |
* @return {String} | |
*/ | |
const matchMask = (input = '') => { | |
// Remove a string from the input | |
if (maskReplaced.length > input.length) { | |
maskReplaced = maskReplaced.slice(0, input.length); | |
i = maskReplaced.length; | |
return maskReplaced.trim(); | |
} | |
// Do not update the string if position > length of da mask | |
if (maskLength > i) { | |
// Append anything !X | |
if ('X' !== mask.charAt(i)) { | |
maskReplaced += mask.charAt(i); | |
i++; | |
} | |
maskReplaced += input.charAt(input.length - 1); | |
} | |
i++; | |
return maskReplaced.trim(); | |
}; | |
/** | |
* Convert a string to match the pattern | |
* @param {String} input | |
* @return {String} | |
*/ | |
const full = input => { | |
maskReplaced = ''; i = 0; | |
return input | |
.split('') | |
.reduce((acc, key) => acc = matchMask(acc + key), ''); | |
}; | |
/** | |
* Return a string without its mask | |
* @param {String} input | |
* @return {String} | |
*/ | |
const filtered = (input = '') => { | |
return input | |
.split('') | |
.filter(key => -1 === maskSepators.indexOf(key)) | |
.join('') | |
.trim(); | |
}; | |
const size = () => mask.length; | |
/** | |
* Convert an input masked to another one masked | |
* @param {String} input | |
* @return {String} | |
*/ | |
const update = (input = '') => full(filtered(input.trim())); | |
return {update, matchMask, full, filtered, size}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
With an event listener: