-
Notifications
You must be signed in to change notification settings - Fork 0
/
step6.js
63 lines (55 loc) · 1.29 KB
/
step6.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
const props = {
a: String,
b: Number,
c: {
type: Number,
require: true
}
}
// 还不知道如何上手,但是从字面意思,我先直接翻译一个策略对象
const strategies = {
a: function(value){
if (value === undefined) return
if(typeof value !== 'string') {
return console.error('value a must be string')
}
},
b: function(value){
if (value === undefined) return
if (!/number/.test(typeof value)){
return console.error('value b must be number')
}
},
c: function(value) {
if (value === undefined) {
return console.error('this c value is require')
} else if (value.constructor !== Number) {
return console.error('value c must be number')
}
}
}
function Vaildator (){
this.cache = []
}
// 我模拟一下for循环 把所有属性全部添加到策略缓存
Vaildator.prototype.validate = function (data) {
for (let attr in props) {
this.cache.push(() => strategies[attr].call(null, data[attr]))
}
return this.run()
}
Vaildator.prototype.run = function () {
for(let i = 0, item; item = this.cache[i++];) {
if (item()) return item();
}
}
const data = {
// a: 111,
a: '111',
// b: 'str',
b: 123,
c: 123
// c: '123'
}
const err = new Vaildator().validate(data);
err && console.log(err)