-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
90 lines (81 loc) · 2.51 KB
/
index.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
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
'use strict';
const isUrl = require('./predicates/url');
const isUri = require('./predicates/uri');
const isWebUrl = require('./predicates/webUrl');
const isHexColor = require('./predicates/hexColor');
const isString = require('./predicates/string');
const isArray = require('./predicates/array');
const isNull = require('./predicates/null');
const isUndefined = require('./predicates/undefined');
const isExisty = require('./predicates/existy');
const isInteger = require('./predicates/integer');
const isFinite = require('./predicates/finite');
const isNatural = require('./predicates/natural');
const isNumber = require('./predicates/number');
const isBuffer = require('./predicates/buffer');
const isBoolean = require('./predicates/boolean');
const isFunction = require('./predicates/function');
const isPlainObject = require('./predicates/plainObject');
const isStream = require('./predicates/stream');
const isDate = require('./predicates/date');
const isEmail = require('./predicates/email');
const predicates = {
uri: isUri,
url: isUrl,
webUrl: isWebUrl,
hexColor: isHexColor,
string: isString,
array: isArray,
existy: isExisty,
integer: isInteger,
finite: isFinite,
natural: isNatural,
number: isNumber,
buffer: isBuffer,
boolean: isBoolean,
plainObject: isPlainObject,
date: isDate,
null: isNull,
undefined: isUndefined,
function: isFunction,
stream: isStream,
email: isEmail,
};
const api = { all: {}, optional: {} };
// Build API
Object.getOwnPropertyNames(predicates).forEach((predicateName) => {
const predicate = predicates[predicateName];
api[predicateName] = predicate;
api.all[predicateName] = (values, options) => validateAll(values, predicate, options);
api.optional[predicateName] = (value, options) => validateOptional(value, predicate, options);
});
/**
* Validates a list of values
*
* @param {Array<*>} values - Values
* @param {function} predicate - predicate
* @param {object} options - Options
* @returns {Boolean}
*/
function validateAll(values, predicate, options) {
if (!isArray(values)) {
return false;
}
return values.every(value => predicate(value, options));
}
/**
* Validates an optional values
* An optional value will always validate to true if null/undefined
*
* @param {*} value - Value
* @param {function} predicate - predicate
* @param {object} options - Options
* @returns {Boolean}
*/
function validateOptional(value, predicate, options) {
if (!isExisty(value)) {
return true;
}
return predicate(value, options);
}
module.exports = api;