-
Notifications
You must be signed in to change notification settings - Fork 0
/
step8.js
101 lines (89 loc) · 2.38 KB
/
step8.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
92
93
94
95
96
97
98
99
100
101
const props = {
a: String,
b: [String, Number],
// b: [String, Number, Boolean],
c: {
type: Number,
require: true
}
}
const strategies = {
String: function(value, name){
if(typeof value !== 'string') {
return console.error("the type of variable:"+ name + ' must be string')
}
},
Number: function(value, name){
if (!/number/.test(typeof value)){
return console.error("the type of variable:"+ name + ' must be number')
}
},
require: function(value, name) {
if (value === undefined) {
return console.error("vriable:"+ name + ' is require')
}
},
// 为了迎合 策略b 的情况,就写了新的策略
oneOfTheType: function(value, name, types) {
types.forEach((val, idx, arr) => {
arr[idx] = val.name.toLowerCase()
});
const isOneOfTheType = types.includes(typeof value)
if (!isOneOfTheType) {
return console.error('vaiable:'+name+' must be one of the types')
}
}
}
function Vaildator (){
this.cache = []
}
Vaildator.prototype.validate = function (data) {
for (let attr in props) {
let rule = props[attr];
let value = data[attr];
if (typeof rule === 'function') {
if (!value) return
let ruleName = rule.name;
this.cache.push(() => {
return strategies[ruleName].apply(null, [value, attr])
})
// 添加了 策略b 情况的判断
} else if (rule.length) {
this.cache.push(() => {
return strategies.oneOfTheType.apply(null, [value, attr, rule])
})
} else if (rule instanceof Object) {
if(rule.require) {
if (!value) {
this.cache.push(() => {
return strategies.require.apply(null, [undefined, attr])
})
} else {
let ruleName = props[attr].type.name
this.cache.push(() => {
return strategies[ruleName].apply(null, [value, attr])
})
}
}
}
}
return this.run()
}
Vaildator.prototype.run = function () {
for(let i = 0, item; item = this.cache[i++];) {
if (item()) return item();
}
}
const data = {
// a: 123,
a: 'str',
// b: 'str',
b: 123,
// b: true,
c: 123
// c: 'str'
}
// 恩,这个可能是 initState(vm) 在created hook调用之前
// https://ustbhuangyi.github.io/vue-analysis/data-driven/new-vue.html
const err = new Vaildator().validate(data);
err && console.log(err)