-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
57 lines (50 loc) · 1.14 KB
/
index.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
function Maybe(value) {
if (value === null || value === undefined)
return new Proxy(Nothing, handler)
else if (typeof value === 'function')
return new Proxy(value, handler)
else
return new Proxy(new MaybeContainer(value), handler)
}
function Nothing() {}
Nothing.andThen = function() {
return Maybe(null);
}
const handler = {
get(target, key) {
if (key === 'value' || key === 'andThen') {
if (target[key] === undefined)
return null;
else
return target[key]
} else {
return target.andThen(value => {
if (typeof value[key] === 'function'){
return value[key].bind(value)
} else {
return value[key]
}
})
}
},
apply(target, thisArg, args) {
if (target.value !== Nothing) {
return Maybe(target.apply(thisArg, args))
} else {
return Maybe(Nothing)
}
},
}
class MaybeContainer {
constructor(value) {
this.value = value;
}
andThen(fn) {
if (this.value === Nothing || this.value === null) {
return Maybe(Nothing)
} else {
return Maybe(fn(this.value))
}
}
}
module.exports = { Maybe }