forked from jquense/yup
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCondition.js
53 lines (39 loc) · 1.33 KB
/
Condition.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
import has from 'lodash/has';
import isSchema from './util/isSchema';
class Condition {
constructor(refs, options) {
this.refs = refs;
if (typeof options === 'function') {
this.fn = options;
return;
}
if (!has(options, 'is'))
throw new TypeError('`is:` is required for `when()` conditions');
if (!options.then && !options.otherwise)
throw new TypeError(
'either `then:` or `otherwise:` is required for `when()` conditions',
);
let { is, then, otherwise } = options;
let check =
typeof is === 'function'
? is
: (...values) => values.every(value => value === is);
this.fn = function(...args) {
let options = args.pop();
let schema = args.pop();
let branch = check(...args) ? then : otherwise;
if (!branch) return undefined;
if (typeof branch === 'function') return branch(schema);
return schema.concat(branch.resolve(options));
};
}
resolve(base, options) {
let values = this.refs.map(ref => ref.getValue(options));
let schema = this.fn.apply(base, values.concat(base, options));
if (schema === undefined || schema === base) return base;
if (!isSchema(schema))
throw new TypeError('conditions must return a schema object');
return schema.resolve(options);
}
}
export default Condition;