-
Notifications
You must be signed in to change notification settings - Fork 4
/
match.js
56 lines (49 loc) · 1.59 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
/**
* Use this to match based on conditions more easily.
*/
;(function () {
"use strict"
var Vnode, helpers
if (typeof module === "object" && module && module.exports) {
Vnode = require("mithril/render/vnode")
helpers = module.exports
} else if (typeof m === "function") {
Vnode = m.vnode
helpers = m.helpers || (m.helpers = {})
} else {
throw new Error("Mithril must be loaded first!")
}
function resolve(then) {
return Vnode('[', null, null, [Vnode.normalize(then)])
}
helpers.when = function (cond, then, orElse) {
cond = !!cond
return Vnode("[", null, null, [
Vnode("[", cond, null, [Vnode.normalize(cond ? then() : orElse())])
])
}
helpers.cond = function () {
var children = []
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i]
children.push(arg.if ? resolve(arg.then()) : null)
}
return Vnode('[', null, null, children)
}
helpers.match = function (value) {
var children = []
if (value === value) {
for (var i = 1; i < arguments.length; i++) {
var arg = arguments[i]
children.push(arg.if === value ? resolve(arg.then()) : null)
}
} else {
for (var i = 1; i < arguments.length; i++) {
var arg = arguments[i]
var cond = arg.if
children.push(cond !== cond ? resolve(arg.then()) : null)
}
}
return Vnode('[', null, null, children)
}
})()