-
Notifications
You must be signed in to change notification settings - Fork 0
/
coercer.js
56 lines (49 loc) · 2.04 KB
/
coercer.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
const Maybe = require('crocks/Maybe');
const safe = require('crocks/Maybe/safe');
const curry = require('crocks/helpers/curry');
const isNumber = require('crocks/predicates/isNumber');
const isString = require('crocks/predicates/isString');
const isBool = require('crocks/predicates/isBoolean');
const isInt = require('crocks/predicates/isInteger');
const safeNumber = safe(isNumber);
const safeString = safe(isString);
const safeBool = safe(isBool);
const safeInt = safe(isInt);
module.exports = curry((errorBuilder, value) => {
const onError = () => errorBuilder(value);
const validationChainCreator = maybeValue => (...validators) => {
const isValid = validators.reduce(
(res, validator) => res && maybeValue.map(validator).option(false),
true,
);
const result = isValid ? maybeValue : Maybe.Nothing();
return {
value: () => result.either(onError, x => x),
};
};
const defaultReturnCreator = v => ({
validate: validationChainCreator(v),
value: () => v.either(onError, x => x),
});
const coercers = {
toNumber: () => defaultReturnCreator(safeNumber(value * 1)),
toNumberStrict: () => defaultReturnCreator(safeNumber(value)),
toInt: (base = 10) => defaultReturnCreator(safeInt(parseInt(value, base))),
toFloat: (base = 10) => defaultReturnCreator(safeNumber(parseFloat(value, base))),
toString: () => defaultReturnCreator(safeString(`${value}`)),
toStringStrict: () => defaultReturnCreator(safeString(value)),
toBool: curry((trueValues = ['true', '1'], falseValues = ['false', '0', 'undefined', 'null']) => {
const stringValue = coercers.toString().value();
// eslint-disable-next-line no-nested-ternary
const bool = trueValues.indexOf(stringValue) !== -1
? Maybe.of(true)
: falseValues.indexOf(stringValue) !== -1
? Maybe.of(false)
: Maybe.Nothing();
return defaultReturnCreator(bool);
}),
toBoolStrict: () => defaultReturnCreator(safeBool(value)),
any: () => defaultReturnCreator(Maybe.of(value)),
};
return coercers;
});