forked from probil/v-mask
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmaskToRegExpMask.js
52 lines (48 loc) · 1.66 KB
/
maskToRegExpMask.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { defaultMaskReplacers, NEXT_CHAR_OPTIONAL } from './constants';
import { castToRegexp, makeRegexpOptional } from './utils/regexp';
function maskToRegExpMask(mask, maskReplacers = defaultMaskReplacers) {
return mask
.map((char, index, array) => {
const maskChar = maskReplacers[char] || char;
const previousChar = array[index - 1];
const previousMaskChar = maskReplacers[previousChar] || previousChar;
if (maskChar === NEXT_CHAR_OPTIONAL) {
return null;
}
if (previousMaskChar === NEXT_CHAR_OPTIONAL) {
return makeRegexpOptional(castToRegexp(maskChar));
}
return maskChar;
})
.filter(Boolean);
}
/**
* Converts mask from `v-mask` string format to `text-mask-core` format
* @param {String} stringMask
* @param {object<string, RegExp|NEXT_CHAR_OPTIONAL>} maskReplacers
* @return {RegExp[]}
*/
export function stringMaskToRegExpMask(stringMask, maskReplacers = defaultMaskReplacers) {
return maskToRegExpMask(stringMask.split(''), maskReplacers);
}
/**
* Converts mask from `v-mask` array format to `text-mask-core` format
* @param {Array.<String|RegExp>} arrayMask
* @param {object<string, RegExp|NEXT_CHAR_OPTIONAL>} maskReplacers
* @return {RegExp[]}
*/
export function arrayMaskToRegExpMask(arrayMask, maskReplacers = defaultMaskReplacers) {
const flattenedMask = arrayMask
.map((part) => {
if (part instanceof RegExp) {
return part;
}
if (typeof part === 'string') {
return part.split('');
}
return null;
})
.filter(Boolean)
.reduce((mask, part) => mask.concat(part), []);
return maskToRegExpMask(flattenedMask, maskReplacers);
}