-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstep7.js
87 lines (78 loc) · 2.14 KB
/
step7.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
const props = {
a: String,
b: [String, Number],
c: {
type: Number,
require: true
}
}
// 为了更友好的提示,更精准的定位,我把属性名加上
// 策略名称对应起来,c策略可以更细化
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')
}
}
}
function Vaildator (){
this.cache = []
}
// 虽然上一步把所有属性全部添加到了策略缓存
// 随便写了几种判断变量类型的方法,百度一下有多种方法,各有利弊
// 满足现有需求就好,只写个demo验证一下策略模式,没打算写的很完善
// 算是模拟关联上了props的匹配关系
Vaildator.prototype.validate = function (data) {
for (let attr in props) {
let rule = props[attr];
let value = data[attr];
// 辨别 策略a 的写法
if (typeof rule === 'function') {
if (!value) return
let ruleName = rule.name;
this.cache.push(() => {
return strategies[ruleName].apply(null, [value, attr])
})
// 辨别 策略c 的写法
} 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: '123',
// b: 'str',
// b: 123,
// c: 123
// c: '123'
}
const err = new Vaildator().validate(data);
err && console.log(err)