blob: 1ffa24e2c590d0e14adcf0b2abc9eb35319a56d5 (
plain) (
blame)
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
|
import { default as types } from './types';
type matchType<T = any>
= (boolean | ((T) => boolean));
export function match(template: Object, value?: Object): matchType<Object> {
if (value === undefined) {
return match.bind(null, template);
}
for (let k of Object.keys(template)) {
if (!template[k](value[k])) {
return false;
}
}
return true;
}
export function exact(template: Object, value?: Object): matchType<Object> {
if (value === undefined) {
return exact.bind(null, template);
}
let k1 = Object.keys(template);
let k2 = Object.keys(value);
return match(template, value)
&& k2.every((x) => k1.indexOf(x) < 0);
}
export function optional(template: Function, value?: any): matchType<any> {
if (value === undefined) {
return optional.bind(null, template);
}
return types.undefined(value)
|| template(value);
}
export function alternative(templates: any[], value?: any): matchType<any> {
if (value === undefined) {
return alternative.bind(null, templates);
}
if (templates.length === 0) {
return false;
} else {
let t = templates.map((x) => {
if (types.function(x)) {
return x;
} else if (types.object(x)) {
return match(x);
} else {
return (v) => x === v;
}
});
return t.some((x) => x(value));
}
}
export function array(template: Object, values?: Array<Object>):
matchType<Array<Object>> {
if (values === undefined) {
return array.bind(null, template);
}
let m = match(template) as ((Object) => boolean);
return values.every(m);
}
|