-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathType.js
More file actions
55 lines (48 loc) · 1.39 KB
/
Type.js
File metadata and controls
55 lines (48 loc) · 1.39 KB
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
function typeError(result) {
throw new TypeError(`Input type ${result} is not a valid data type`);
}
function Type(types, otherwise = typeError) {
// Add types to scope
this.types = types.map(
(T) => {
const typeName = T.name || T.prototype.constructor;
if (!typeName) {
throw new TypeError(`${T} is not a valid data type`);
}
return typeName;
},
);
if (typeof otherwise !== 'function') {
throw new Error('You need supply an "otherwise" handler function');
}
// Add to scope
this.otherwise = otherwise;
this.isValidType = (a) => {
if ([null, undefined].includes(a)) {
throw new TypeError(`Type safety doesn't play well with null or undefined values`);
}
const name = (a).name || ((a).constructor && (a).constructor.name);
return this.types.includes(name);
}
// Box is simply a container that allows us to run functions over the contents
this.Box = (a) => ({
a,
inspect: () => `Box(${a})`,
map: (f) => {
const result = f(a);
return this.isValidType(result) ? this.Box(result) : this.otherwise(result);
},
chain: (f) => {
const result = f(a);
return this.isValidType(result) ? result : this.otherwise(result);
},
join: () => a,
});
return (a) => {
if (this.isValidType(a)) {
return this.Box(a);
}
return this.otherwise(a);
}
}
module.exports = Type;