-
Notifications
You must be signed in to change notification settings - Fork 10
/
check-more-types.js
803 lines (704 loc) · 18.6 KB
/
check-more-types.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
(function checkMoreTypes() {
'use strict';
/**
Custom assertions and predicates around https://github.com/philbooth/check-types.js
Created by Kensho https://github.com/kensho
Copyright @ 2014 Kensho https://www.kensho.com/
License: MIT
@module check
*/
if (typeof Function.prototype.bind !== 'function') {
throw new Error('Missing Function.prototype.bind, please load es5-shim first');
}
// utility method
function curry2(fn) {
return function curried(a) {
if (arguments.length > 2) {
throw new Error('Curry2 function ' + fn.name +
' called with too many arguments ' + arguments.length);
}
if (arguments.length === 2) {
return fn(arguments[0], arguments[1]);
}
return function second(b) {
return fn(a, b);
};
};
}
// most of the old methods from check-types.js
function isFn(x) { return typeof x === 'function'; }
function isString(x) { return typeof x === 'string'; }
function unemptyString(x) {
return isString(x) && x;
}
function isObject(x) {
return typeof x === 'object' &&
!Array.isArray(x) &&
!isNull(x) &&
!isDate(x);
}
function isEmptyObject(x) {
return isObject(x) &&
Object.keys(x).length === 0;
}
function isNumber(x) {
return typeof x === 'number' &&
!isNaN(x) &&
x !== Infinity &&
x !== -Infinity;
}
function isInteger(x) {
return isNumber(x) && x % 1 === 0;
}
function isFloat(x) {
return isNumber(x) && x % 1 !== 0;
}
function isNull(x) { return x === null; }
function positiveNumber(x) {
return isNumber(x) && x > 0;
}
function negativeNumber(x) {
return isNumber(x) && x < 0;
}
function isDate(x) {
return x instanceof Date;
}
function isRegExp(x) {
return x instanceof RegExp;
}
function instance(x, type) {
return x instanceof type;
}
function hasLength(x, k) {
return (Array.isArray(x) || isString(x)) && x.length === k;
}
/**
Checks if the given index is valid in an array or string or -1
@method found
*/
function found(index) {
return index >= 0;
}
function startsWith(prefix, x) {
return isString(prefix) &&
isString(x) &&
x.indexOf(prefix) === 0;
}
/**
Checks if the type of second argument matches the name in the first
@method type
*/
function type(expectedType, x) {
return typeof x === expectedType;
}
var startsWithHttp = startsWith.bind(null, 'http://');
var startsWithHttps = startsWith.bind(null, 'https://');
function webUrl(x) {
return isString(x) &&
(startsWithHttp(x) || startsWithHttps(x));
}
function every(predicateResults) {
var property, value;
for (property in predicateResults) {
if (predicateResults.hasOwnProperty(property)) {
value = predicateResults[property];
if (isObject(value) && every(value) === false) {
return false;
}
if (value === false) {
return false;
}
}
}
return true;
}
function map(things, predicates) {
var property, result = {}, predicate;
for (property in predicates) {
if (predicates.hasOwnProperty(property)) {
predicate = predicates[property];
if (isFn(predicate)) {
result[property] = predicate(things[property]);
} else if (isObject(predicate)) {
result[property] = map(things[property], predicate);
}
}
}
return result;
}
var check = {
maybe: {},
verify: {},
not: {},
every: every,
map: map
};
/**
Checks if argument is defined or not
This method now is part of the check-types.js
@method defined
*/
function defined(value) {
return typeof value !== 'undefined';
}
/**
Checks if argument is a valid Date instance
@method validDate
*/
function validDate(value) {
return check.date(value) &&
check.number(Number(value));
}
/**
Checks if it is exact semver
@method semver
*/
function semver(s) {
return check.unemptyString(s) &&
/^\d+\.\d+\.\d+$/.test(s);
}
/**
Returns true if the argument is primitive JavaScript type
@method primitive
*/
function primitive(value) {
var type = typeof value;
return type === 'number' ||
type === 'boolean' ||
type === 'string';
}
/**
Returns true if the value is a number 0
@method zero
*/
function zero(x) {
return typeof x === 'number' && x === 0;
}
/**
same as ===
@method same
*/
function same(a, b) {
return a === b;
}
/**
Returns true if the index is valid for give string / array
@method index
*/
function index(list, k) {
return defined(list) &&
has(list, 'length') &&
k >= 0 &&
k < list.length;
}
/**
Returns true if both objects are the same type and have same length property
@method sameLength
*/
function sameLength(a, b) {
return typeof a === typeof b &&
a && b &&
a.length === b.length;
}
/**
Returns true if all items in an array are the same reference
@method allSame
*/
function allSame(arr) {
if (!check.array(arr)) {
return false;
}
if (!arr.length) {
return true;
}
var first = arr[0];
return arr.every(function (item) {
return item === first;
});
}
/**
Returns true if given item is in the array
@method oneOf
*/
function oneOf(arr, x) {
check.verify.array(arr, 'expected an array');
return arr.indexOf(x) !== -1;
}
/**
Returns true for urls of the format `git@....git`
@method git
*/
function git(url) {
return check.unemptyString(url) &&
/^git@/.test(url);
}
/**
Checks if given value is 0 or 1
@method bit
*/
function bit(value) {
return value === 0 || value === 1;
}
/**
Checks if given value is true of false
@method bool
*/
function bool(value) {
return typeof value === 'boolean';
}
/**
Checks if given object has a property
@method has
*/
function has(o, property) {
if (arguments.length !== 2) {
throw new Error('Expected two arguments to check.has, got only ' + arguments.length);
}
return Boolean(o && property &&
typeof property === 'string' &&
typeof o[property] !== 'undefined');
}
/**
Checks if given string is already in lower case
@method lowerCase
*/
function lowerCase(str) {
return check.string(str) &&
str.toLowerCase() === str;
}
/**
Returns true if the argument is an array with at least one value
@method unemptyArray
*/
function unemptyArray(a) {
return check.array(a) && a.length > 0;
}
/**
Returns true if each item in the array passes the predicate
@method arrayOf
@param rule Predicate function
@param a Array to check
*/
function arrayOf(rule, a) {
return check.array(a) && a.every(rule);
}
/**
Returns items from array that do not passes the predicate
@method badItems
@param rule Predicate function
@param a Array with items
*/
function badItems(rule, a) {
check.verify.array(a, 'expected array to find bad items');
return a.filter(notModifier(rule));
}
/**
Returns true if given array only has strings
@method arrayOfStrings
@param a Array to check
@param checkLowerCase Checks if all strings are lowercase
*/
function arrayOfStrings(a, checkLowerCase) {
var v = check.array(a) && a.every(check.string);
if (v && check.bool(checkLowerCase) && checkLowerCase) {
return a.every(check.lowerCase);
}
return v;
}
/**
Returns true if given argument is array of arrays of strings
@method arrayOfArraysOfStrings
@param a Array to check
@param checkLowerCase Checks if all strings are lowercase
*/
function arrayOfArraysOfStrings(a, checkLowerCase) {
return check.array(a) && a.every(function (arr) {
return check.arrayOfStrings(arr, checkLowerCase);
});
}
/**
Checks if object passes all rules in predicates.
check.all({ foo: 'foo' }, { foo: check.string }, 'wrong object');
This is a composition of check.every(check.map ...) calls
https://github.com/philbooth/check-types.js#batch-operations
@method all
@param {object} object object to check
@param {object} predicates rules to check. Usually one per property.
@public
@returns true or false
*/
function all(obj, predicates) {
check.verify.fn(check.every, 'missing check.every method');
check.verify.fn(check.map, 'missing check.map method');
check.verify.object(obj, 'missing object to check');
check.verify.object(predicates, 'missing predicates object');
Object.keys(predicates).forEach(function (property) {
if (!check.fn(predicates[property])) {
throw new Error('not a predicate function for ' + property + ' but ' + predicates[property]);
}
});
return check.every(check.map(obj, predicates));
}
/**
Checks given object against predicates object
@method schema
*/
function schema(predicates, obj) {
return all(obj, predicates);
}
/** Checks if given function raises an error
@method raises
*/
function raises(fn, errorValidator) {
check.verify.fn(fn, 'expected function that raises');
try {
fn();
} catch (err) {
if (typeof errorValidator === 'undefined') {
return true;
}
if (typeof errorValidator === 'function') {
return errorValidator(err);
}
return false;
}
// error has not been raised
return false;
}
/**
Returns true if given value is ''
@method emptyString
*/
function emptyString(a) {
return a === '';
}
/**
Returns true if given value is [], {} or ''
@method empty
*/
function empty(a) {
var hasLength = typeof a === 'string' ||
Array.isArray(a);
if (hasLength) {
return !a.length;
}
if (a instanceof Object) {
return !Object.keys(a).length;
}
return false;
}
/**
Returns true if given value has .length and it is not zero, or has properties
@method unempty
*/
function unempty(a) {
var hasLength = typeof a === 'string' ||
Array.isArray(a);
if (hasLength) {
return a.length;
}
if (a instanceof Object) {
return Object.keys(a).length;
}
return true;
}
/**
Returns true if 0 <= value <= 1
@method unit
*/
function unit(value) {
return check.number(value) &&
value >= 0.0 && value <= 1.0;
}
var rgb = /^#(?:[0-9a-fA-F]{3}){1,2}$/;
/**
Returns true if value is hex RGB between '#000000' and '#FFFFFF'
@method hexRgb
*/
function hexRgb(value) {
return check.string(value) &&
rgb.test(value);
}
// typical git SHA commit id is 40 digit hex string, like
// 3b819803cdf2225ca1338beb17e0c506fdeedefc
var shaReg = /^[0-9a-f]{40}$/;
/**
Returns true if the given string is 40 digit SHA commit id
@method commitId
*/
function commitId(id) {
return check.string(id) &&
id.length === 40 &&
shaReg.test(id);
}
// when using git log --oneline short ids are displayed, first 7 characters
var shortShaReg = /^[0-9a-f]{7}$/;
/**
Returns true if the given string is short 7 character SHA id part
@method shortCommitId
*/
function shortCommitId(id) {
return check.string(id) &&
id.length === 7 &&
shortShaReg.test(id);
}
//
// helper methods
//
if (!check.defend) {
var checkPredicates = function checksPredicates(fn, predicates, args) {
check.verify.fn(fn, 'expected a function');
check.verify.array(predicates, 'expected list of predicates');
check.verify.defined(args, 'missing args');
var k = 0, // iterates over predicates
j = 0, // iterates over arguments
n = predicates.length;
for (k = 0; k < n; k += 1) {
var predicate = predicates[k];
if (!check.fn(predicate)) {
continue;
}
if (!predicate.call(null, args[j])) {
var msg = 'Argument ' + (j + 1) + ': ' + args[j] + ' does not pass predicate';
if (check.unemptyString(predicates[k + 1])) {
msg += ': ' + predicates[k + 1];
}
throw new Error(msg);
}
j += 1;
}
return fn.apply(null, args);
};
check.defend = function defend(fn) {
var predicates = Array.prototype.slice.call(arguments, 1);
return function () {
return checkPredicates(fn, predicates, arguments);
};
};
}
/**
Combines multiple predicate functions to produce new OR predicate
@method or
*/
function or() {
var predicates = Array.prototype.slice.call(arguments, 0);
if (!predicates.length) {
throw new Error('empty list of arguments to or');
}
return function orCheck() {
var values = Array.prototype.slice.call(arguments, 0);
return predicates.some(function (predicate) {
try {
return check.fn(predicate) ?
predicate.apply(null, values) : Boolean(predicate);
} catch (err) {
// treat exceptions as false
return false;
}
});
};
}
/**
Combines multiple predicate functions to produce new AND predicate
@method or
*/
function and() {
var predicates = Array.prototype.slice.call(arguments, 0);
if (!predicates.length) {
throw new Error('empty list of arguments to or');
}
return function orCheck() {
var values = Array.prototype.slice.call(arguments, 0);
return predicates.every(function (predicate) {
return check.fn(predicate) ?
predicate.apply(null, values) : Boolean(predicate);
});
};
}
/**
* Public modifier `not`.
*
* Negates `predicate`.
* copied from check-types.js
*/
function notModifier(predicate) {
return function () {
return !predicate.apply(null, arguments);
};
}
if (!check.mixin) {
/** Adds new predicate to all objects
@method mixin */
check.mixin = function mixin(fn, name) {
if (isString(fn) && isFn(name)) {
var tmp = fn;
fn = name;
name = tmp;
}
if (!isFn(fn)) {
throw new Error('expected predicate function');
}
if (!unemptyString(name)) {
name = fn.name;
}
if (!unemptyString(name)) {
throw new Error('predicate function missing name\n' + fn.toString());
}
function registerPredicate(obj, name, fn) {
if (!isObject(obj)) {
throw new Error('missing object ' + obj);
}
if (!unemptyString(name)) {
throw new Error('missing name');
}
if (!isFn(fn)) {
throw new Error('missing function');
}
if (!obj[name]) {
obj[name] = fn;
}
}
/**
* Public modifier `maybe`.
*
* Returns `true` if `predicate` is `null` or `undefined`,
* otherwise propagates the return value from `predicate`.
* copied from check-types.js
*/
function maybeModifier(predicate) {
return function () {
if (!check.defined(arguments[0]) || check.nulled(arguments[0])) {
return true;
}
return predicate.apply(null, arguments);
};
}
/**
* Public modifier `verify`.
*
* Throws if `predicate` returns `false`.
* copied from check-types.js
*/
function verifyModifier(predicate, defaultMessage) {
return function () {
var message;
if (predicate.apply(null, arguments) === false) {
message = arguments[arguments.length - 1];
throw new Error(check.unemptyString(message) ? message : defaultMessage);
}
};
}
registerPredicate(check, name, fn);
registerPredicate(check.maybe, name, maybeModifier(fn));
registerPredicate(check.not, name, notModifier(fn));
registerPredicate(check.verify, name, verifyModifier(fn, name + ' failed'));
};
}
if (!check.then) {
/**
Executes given function only if condition is truthy.
@method then
*/
check.then = function then(condition, fn) {
return function () {
var ok = typeof condition === 'function' ?
condition.apply(null, arguments) : condition;
if (ok) {
return fn.apply(null, arguments);
}
};
};
}
var promiseSchema = {
then: isFn
};
// work around reserved keywords checks
promiseSchema['catch'] = isFn;
promiseSchema['finally'] = isFn;
var hasPromiseApi = schema.bind(null, promiseSchema);
/**
Returns true if argument implements promise api (.then, .catch, .finally)
@method promise
*/
function isPromise(p) {
return check.object(p) && hasPromiseApi(p);
}
/**
Shallow strict comparison
@method equal
*/
function equal(a, b) {
return a === b;
}
// new predicates to be added to check object. Use object to preserve names
var predicates = {
nulled: isNull,
fn: isFn,
string: isString,
unemptyString: unemptyString,
object: isObject,
number: isNumber,
array: Array.isArray,
positiveNumber: positiveNumber,
negativeNumber: negativeNumber,
defined: defined,
same: same,
allSame: allSame,
bit: bit,
bool: bool,
has: has,
lowerCase: lowerCase,
unemptyArray: unemptyArray,
arrayOfStrings: arrayOfStrings,
arrayOfArraysOfStrings: arrayOfArraysOfStrings,
all: all,
schema: schema,
raises: raises,
empty: empty,
found: found,
emptyString: emptyString,
unempty: unempty,
unit: unit,
hexRgb: hexRgb,
sameLength: sameLength,
commitId: commitId,
shortCommitId: shortCommitId,
index: index,
git: git,
arrayOf: arrayOf,
badItems: badItems,
oneOf: curry2(oneOf),
promise: isPromise,
validDate: validDate,
equal: curry2(equal),
or: or,
and: and,
primitive: primitive,
zero: zero,
date: isDate,
regexp: isRegExp,
instance: instance,
emptyObject: isEmptyObject,
length: hasLength,
floatNumber: isFloat,
intNumber: isInteger,
startsWith: startsWith,
webUrl: webUrl,
semver: semver,
type: curry2(type)
};
Object.keys(predicates).forEach(function (name) {
check.mixin(predicates[name], name);
});
if (typeof module === 'object') {
module.exports = check;
}
// if we are loaded under Node, but "window" object is available, put a reference
// there too - maybe we are running inside a synthetic browser environment
if (typeof window === 'object') {
window.check = check;
}
if (typeof global === 'object') {
global.check = check;
}
}());