/
merge-stop.js
69 lines (55 loc) · 1.42 KB
/
merge-stop.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
'use strict'
const omit = require('lodash/omit')
const createMatchStop = require('./match-stop-or-station')
const mergeObjects = require('./lib/merge-objects')
const createMergeId = require('./lib/merge-id')
const mergeIds = require('./lib/merge-ids')
const createMergeStop = (A, B, opt = {}) => {
const matchStop = createMatchStop(A, B)
const mergeSubStops = (stopsA, stopsB) => {
if (stopsB.length === 0) return stopsA
if (stopsA.length === 0) return stopsB
// todo: what about stops in B that are not in A?
return stopsA.map((stA) => {
const stB = stopsB.find(matchStop(stA))
return stB ? mergeStop(stA, stB) : stA
})
}
const mergeStop = (stopA, stopB) => {
const {
endpointName: endpNameA,
} = A
const {
endpointName: endpNameB,
} = B
const {
preferB,
} = {
preferB: {},
...opt,
}
const {
id: mergeIdPreferB,
} = {
id: false,
...preferB,
}
const mergeId = createMergeId(mergeIdPreferB)
const ids = mergeIds('id', endpNameA, stopA, endpNameB, stopB)
if (!stopB) return {...stopA, ids}
if (!stopA) return {...stopB, id: null, ids}
const res = {
...mergeObjects(stopA, stopB),
id: mergeId(stopA.id, stopB.id),
ids,
}
if (stopA.station) {
res.station = mergeStop(stopA.station, stopB.station)
}
const subStops = mergeSubStops(stopA.stops || [], stopB.stops || [])
if (subStops.length > 0) res.stops = subStops
return res
}
return mergeStop
}
module.exports = createMergeStop