-
Notifications
You must be signed in to change notification settings - Fork 4
/
match.mjs
37 lines (32 loc) · 987 Bytes
/
match.mjs
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
/**
* Use this to match based on conditions more easily.
*/
import Vnode from "mithril/render/vnode"
function resolve(then) {
return Vnode('[', null, null, [Vnode.normalize(then)])
}
export function when(cond, then, orElse) {
cond = !!cond
return Vnode("[", null, null, [
Vnode("[", cond, null, [Vnode.normalize(cond ? then() : orElse())])
])
}
export function cond(...args) {
for (let i = 0; i < args.length; i++) {
args[i] = args[i].if ? resolve(args[i].then()) : null
}
return Vnode('[', null, null, args)
}
export function match(value, ...args) {
if (value === value) {
for (let i = 0; i < args.length; i++) {
args[i] = args[i].if === value ? resolve(args[i].then()) : null
}
} else {
for (let i = 0; i < args.length; i++) {
const cond = args[i].if
args[i] = cond !== cond ? resolve(args[i].then()) : null
}
}
return Vnode('[', null, null, args)
}