-
Notifications
You must be signed in to change notification settings - Fork 2
/
simplicity.es6.js
45 lines (41 loc) · 1005 Bytes
/
simplicity.es6.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
// Usage:
// import match from 'simplicity'
// match('a')
// .with(x => x == 'a', 'letter is A')
// .else(() => 'unknown letter')
// .do()
export default function match(matchOn) {
var self = {};
var cases = [];
var elseCase = null;
self.with = (condition, result) => {
cases.push({
condition: condition,
result: result
});
return self;
};
self.else = result => {
elseCase = result || (() => result);
return self;
};
self.do = (value) => {
value = (value || value === false) ? value : matchOn;
for (var i in cases) {
var result = typeof cases[i].condition == 'function'
? cases[i].condition(value)
: cases[i].condition == value;
if (result) {
return typeof cases[i].result == 'function'
? cases[i].result(value)
: cases[i].result;
}
}
if (elseCase || elseCase === false) {
return typeof elseCase == 'function' ? elseCase(value) : elseCase;
}
throw 'Incomplete pattern match';
};
self.toFunc = () => self.do;
return self;
}