-
Notifications
You must be signed in to change notification settings - Fork 0
/
match.js
136 lines (132 loc) · 2.89 KB
/
match.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
var $ = {}, _ = {}, etc = {};
function matches(value, pattern){
var result = {vars: [], matched: false};
if (pattern === _)
{
result.matched = true;
return result;
}
if (pattern === $)
{
result.matched = true;
result.vars.push(value);
return result;
}
//undefined
if (typeof pattern == 'undefined')
{
result.matched = typeof value == 'undefined';
return result;
}
//null
if (pattern === null){
result.matched = value === null;
return result;
}
//primitives
if (['boolean', 'number', 'string'].indexOf(typeof pattern) !== -1)
{
result.matched = value === pattern;
return result;
}
//regexps
if (pattern instanceof RegExp)
{
result.matched = false;
if (typeof value == 'string')
{
var match = value.match(pattern);
result.matched = !!match;
if (result.matched)
{
result.vars.push(match);
}
}
return result;
}
//arrays
if (Array.isArray(pattern))
{
result.matched = true;
if(!Array.isArray(value)){
result.matched = false;
return result;
}
for(var i = 0; i < pattern.length; i++)
{
if(pattern[i] == etc){
result.matched = true;
break;
}
var matchInfo = matches(value[i], pattern[i]);
if (!matchInfo.matched)
{
result.matched = false;
break;
}
result.vars = result.vars.concat(matchInfo.vars);
}
return result;
}
//objects
if (typeof pattern === 'object')
{
result.matched = true;
if(typeof value != 'object'){
result.matched = false;
}
for(var prop in pattern)
{
var matchInfo = matches(value[prop], pattern[prop]);
if (!matchInfo.matched)
{
result.matched = false;
break;
}
result.vars = result.vars.concat(matchInfo.vars);
}
return result;
}
//functions
if (typeof pattern == 'function')
{
result.matched = pattern(value);
}
return result;
}
function match(/*pattern1, pattern2, ...*/){
var patterns = Array.prototype.slice.call(arguments);
if (patterns.length === 0)
{
throw {
name: 'InvocationError',
message: 'match should be called with one or more arguments'
};
}
var vars = [];
return function(object){
for(var i = 0; pattern = patterns[i]; i++){
var matchResult = matches(object, pattern[0]);
if (matchResult.matched)
{
if (pattern[1] instanceof Function)
{
var result = pattern[1].apply(object, matchResult.vars);
return (result instanceof Number || result instanceof String || result instanceof Boolean) ?
result.valueOf() : result;
}
return pattern[1];
}
}
throw {
name: 'MatchError',
message: 'unable to match ' + object + ' against ' + patterns
};
};
}
module.exports = {
match: match,
$: $,
_: _,
etc: etc
};