-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbaccano.js
59 lines (47 loc) · 1.15 KB
/
baccano.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
58
59
const SUCCESS = Symbol.for('SUCCESS')
const UNSPECIFIED_ERROR = Symbol.for('UNSPECIFIED_ERROR')
const SomeError = (errorType, message) => ({
value: () => message,
type: () => errorType
})
const Errors = errors => ({
value: () => errors,
concat: error => Errors([...errors, error])
})
const Success = x => ({
value: () => x,
type: () => SUCCESS
})
const compose = (...fns) => async x => {
let result = [Success(x), Errors([])]
for (const fn of fns) {
result = await fn(result)
}
const [value, errors] = result
const resolved = {
value: value.value(),
errors: errors.value().map(error => ({message: error.value(), type: error.type()}))
}
return resolved
}
const fromUnary = fn => {
return async ([success, errors]) => {
try {
const response = await fn(success.value())
const type = response.type()
if (type === SUCCESS) {
return [response, errors]
} else {
return [success, errors.concat(response)]
}
} catch(err) {
return [success, errors.concat(SomeError(UNSPECIFIED_ERROR, err.message))]
}
}
}
export {
compose,
fromUnary,
Success,
SomeError
}