-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
91 lines (72 loc) · 1.67 KB
/
index.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
function TinyMask(pattern, options) {
var defaultOptions = {
translation: {
'9': function (val) {
return val.replace(/[^0-9]+/g, '');
},
'A': function (val) {
return val.replace(/[^a-zA-Z]+/g, '');
},
'S': function (val) {
return val.replace(/[^a-zA-Z0-9]+/g, '');
},
'*': function (val) {
return val;
}
},
invalidValues: [null, undefined, '']
};
var opt = options || {};
this._options = {
translation: Object.assign(defaultOptions.translation, opt.translation),
invalidValues: Object.assign(defaultOptions.invalidValues, opt.invalidValues),
pattern: pattern
};
this._handlers = [];
for (var i = 0; i < pattern.length; i++) {
var element = pattern[i];
var result = this._options.translation[element] || element;
this._handlers.push(result);
}
};
TinyMask.prototype._isString = function(value) {
return typeof value === "string";
}
TinyMask.prototype.mask = function (value) {
var result = '';
var val = String(value);
if (val.length === 0) return;
var maskSize = this._handlers.length;
var maskResolved = 0;
var valueSize = val.length;
var valueResolved = 0;
while (maskResolved < maskSize) {
var hand = this._handlers[maskResolved];
var char = val[valueResolved];
if (char === undefined) {
break;
}
if (char === hand) {
result += char;
maskResolved++;
valueResolved++
continue;
}
if (this._isString(hand)) {
result += hand;
maskResolved++;
continue;
}
var parsed = hand(char);
if (this._options.invalidValues.indexOf(parsed) < 0) {
result += parsed;
valueResolved++;
}
else {
break;
}
maskResolved++;
}
return result;
}
module.exports = TinyMask;