-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathschedule.js
77 lines (59 loc) · 2.58 KB
/
schedule.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
'use strict'
const a = require('assert')
const is = require('@sindresorhus/is')
const anyOf = require('./lib/any-of')
// The threshold above which we can safely consider a sequence
// as too long, cruise ship routes taken into account.
const twoWeeks = 2 * 7 * 24 * 60 * 60
const isField = (obj, f) => {
return !is.null(obj[f]) && !is.undefined(obj[f])
}
const validateSequenceItems = (_name = 'schedule.sequence') => {
const validateSequenceItem = (sItem, i, sItems) => {
const lastI = sItems.length - 1
const name = _name + '[' + i + ']'
a.ok(is.object(sItem) && !is.array(sItem), name + ' must be an object')
const hasDeparture = isField(sItem, 'departure') || i !== lastI
if (hasDeparture) {
a.strictEqual(typeof sItem.departure, 'number', name + '.departure must be a number')
}
if (i === 0) {
a.strictEqual(sItem.departure, 0, name + '.departure must be `0`')
} else if (i !== lastI) {
a.ok(sItem.departure < twoWeeks, name + '.departure must b a relative value')
}
if (isField(sItem, 'arrival') || i === lastI) {
a.strictEqual(typeof sItem.arrival, 'number', name + '.arrival must be a number')
a.ok(sItem.arrival < twoWeeks, name + '.arrival must b a relative value')
if (hasDeparture) {
a.ok(sItem.arrival < sItem.departure, name + '.arrival must be < ' + name + '.departure')
}
}
}
return validateSequenceItem
}
const validateStarts = (name = 'schedule.starts') => {
const validateStart = (start, i) => {
a.strictEqual(typeof start, 'number', name + '[' + i + '] must be a UNIX timestamp')
// todo: check if in a reasonable range
}
return validateStart
}
const validateSchedule = (val, schedule, name = 'schedule') => {
val.item(val, schedule, name)
a.strictEqual(schedule.type, 'schedule', name + '.type must be `schedule`')
val.ref(val, schedule.id, name + '.id')
anyOf(['route', 'ref'], val, schedule.route, name + '.route')
val.mode(val, schedule.mode, name + '.mode')
if (!is.undefined(schedule.subMode)) {
a.fail(name + '.subMode is reserved and should not be used for now')
}
a.ok(Array.isArray(schedule.sequence), name + '.sequence must be an array')
a.ok(schedule.sequence.length > 0, name + '.sequence can\'t be empty')
schedule.sequence.forEach(validateSequenceItems(name + '.sequence'))
// todo: check if sorted correctly
a.ok(Array.isArray(schedule.starts), name + '.starts must be an array')
a.ok(schedule.starts.length > 0, name + '.starts can\'t be empty')
schedule.starts.forEach(validateStarts(name + '.starts'))
}
module.exports = validateSchedule