This repository has been archived by the owner on Jun 4, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 74
/
reconcile.ts
93 lines (79 loc) · 2.67 KB
/
reconcile.ts
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import * as R from 'ramda';
import {
ChangeAction,
ChangeFailure,
ColumnType,
IColumnType
} from 'dash-table/components/Table/props';
import reconcileAny from './any';
import { coerce as coerceNumber, validate as validateNumber } from './number';
import { coerce as coerceText, validate as validateText } from './text';
import { coerce as coerceDate, validate as validateDate } from './date';
import { OptionalPluck } from 'core/type';
export interface IReconciliation {
action?: ChangeAction;
failure?: ChangeFailure;
success: boolean;
value?: any;
}
type Options = OptionalPluck<IColumnType, 'on_change'> &
OptionalPluck<IColumnType, 'type'> &
OptionalPluck<IColumnType, 'validation'>;
function getCoercer(c: Options): (value: any, c?: any) => IReconciliation {
switch (c.type) {
case ColumnType.Numeric:
return coerceNumber;
case ColumnType.Text:
return coerceText;
case ColumnType.Datetime:
return coerceDate;
case ColumnType.Any:
default:
return reconcileAny;
}
}
function getValidator(c: Options): (value: any, c?: any) => IReconciliation {
switch (c.type) {
case ColumnType.Numeric:
return validateNumber;
case ColumnType.Text:
return validateText;
case ColumnType.Datetime:
return validateDate;
case ColumnType.Any:
default:
return reconcileAny;
}
}
function doAction(value: any, c: Options) {
const action = (c && c.on_change && c.on_change.action) || ChangeAction.Coerce;
switch (action) {
case ChangeAction.Coerce:
return { action, ...getCoercer(c)(value, c) };
case ChangeAction.None:
return { success: true, value, action };
case ChangeAction.Validate:
return { action, ...getValidator(c)(value, c) };
}
}
function doFailureRecovery(result: IReconciliation, c: Options) {
// If c/v unsuccessful, process failure
const failure = (c && c.on_change && c.on_change.failure) || ChangeFailure.Reject;
result.failure = failure;
if (failure === ChangeFailure.Default) {
const validationDefault = c && c.validation && c.validation.default;
const defaultValue = R.isNil(validationDefault) ? null : validationDefault;
result.success = true;
result.value = defaultValue;
} else if (failure === ChangeFailure.Accept) {
result.success = true;
}
return result;
}
export default (value: any, c: Options) => {
let res: IReconciliation = doAction(value, c);
if (res.success) {
return res;
}
return doFailureRecovery(res, c);
};