/
Array.js
70 lines (53 loc) · 2.01 KB
/
Array.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
var Schema = require('../Schema')
, EqualitySchema = require('../patterns/equality')
, anything = require('../patterns/anything').instance
var ArraySchema = module.exports = Schema.extensions.ArraySchema = Schema.extend({
initialize : function(itemSchema, max, min) {
this.itemSchema = itemSchema || anything
this.min = min || 0
this.max = max || Infinity
},
validate : function(instance) {
// Instance must be an instance of Array
if (!(instance instanceof Array)) return false
// Checking length
if (this.min === this.max) {
if (instance.length !== this.min) return false
} else {
if (this.min > 0 && instance.length < this.min) return false
if (this.max < Infinity && instance.length > this.max) return false
}
// Checking conformance to the given item schema
for (var i = 0; i < instance.length; i++) {
if (!this.itemSchema.validate(instance[i])) return false;
}
return true
},
toJSON : Schema.session(function() {
var json = Schema.prototype.toJSON.call(this, true)
if (json['$ref'] != null) return json
json.tpye = 'array'
if (this.min > 0) json.minItems = this.min
if (this.max < Infinity) json.maxItems = this.max
if (this.itemSchema !== anything) json.items = this.itemSchema.toJSON()
return json
})
})
Schema.fromJSON.def(function(sch) {
if (!sch || sch.type !== 'array') return
// Tuple typing is not yet supported
if (sch.items instanceof Array) return
return new ArraySchema(Schema.fromJSON(sch.items), sch.maxItems, sch.minItems)
})
Array.of = function() {
// Possible signatures : (schema)
// (length, schema)
// (minLength, maxLength, schema)
var args = Array.prototype.slice.call(arguments).reverse()
if (args.length === 2) args[2] = args[1]
return new ArraySchema(Schema.fromJS(args[0]), args[1], args[2]).wrap()
}
Array.like = function(other) {
return new EqualitySchema(other).wrap()
}
Array.schema = new ArraySchema().wrap()