1
1
const _ = require ( 'lodash' ) ;
2
2
3
- const defaultLabelGenerator = require ( 'pelias-labels' ) ;
3
+ const defaultLabelGenerator = require ( 'pelias-labels' ) . partsGenerator ;
4
4
5
5
function setup ( labelGenerator ) {
6
6
function middleware ( req , res , next ) {
@@ -10,17 +10,55 @@ function setup(labelGenerator) {
10
10
return middleware ;
11
11
}
12
12
13
+ function getLabelFromLayer ( parts , layer ) {
14
+ const part = parts . find ( p => p . layer === layer ) ;
15
+ return _ . get ( part , 'label' ) ;
16
+ }
17
+
18
+ function filterUnambiguousParts ( part , second ) {
19
+ if ( part . role === 'required' ) {
20
+ return false ;
21
+ }
22
+ const label = getLabelFromLayer ( second . parts , part . layer ) ;
23
+ return label && label !== part . label ;
24
+ }
25
+
26
+ function getBestLayers ( results ) {
27
+ const first = results [ 0 ] ;
28
+ const second = results [ 1 ] ;
29
+ return first . parts . filter ( p => filterUnambiguousParts ( p , second ) ) . map ( p => p . layer ) ;
30
+ }
31
+
13
32
function assignLabel ( req , res , next , labelGenerator ) {
14
33
15
34
// do nothing if there's nothing to process
16
35
if ( ! res || ! res . data ) {
17
36
return next ( ) ;
18
37
}
19
38
39
+ // This object will help for label deduplication
40
+ const dedupLabel = { } ;
41
+
42
+ // First we assign for all result the default label with all required layers
20
43
res . data . forEach ( function ( result ) {
21
- result . label = labelGenerator ( result , _ . get ( req , 'clean.lang.iso6393' ) ) ;
44
+ const { labelParts, separator } = labelGenerator ( result , _ . get ( req , 'clean.lang.iso6393' ) ) ;
45
+ result . label = labelParts . filter ( e => e . role === 'required' ) . map ( e => e . label ) . join ( separator ) ;
46
+ dedupLabel [ result . label ] = dedupLabel [ result . label ] || [ ] ;
47
+ dedupLabel [ result . label ] . push ( { result, labelParts, separator } ) ;
22
48
} ) ;
23
49
50
+ // We check all values with more than one entry
51
+ Object . values ( dedupLabel )
52
+ . filter ( results => results . length > 1 )
53
+ . forEach ( results => {
54
+ // This array will contain all optional layers that should be displayed
55
+ const bestLayers = getBestLayers ( results ) ;
56
+ // We reassign the label with the new value
57
+ results . forEach ( ( { result, labelParts, separator } ) => {
58
+ result . label = labelParts . filter ( e => e . role === 'required' || bestLayers . indexOf ( e . layer ) >= 0 ) . map ( e => e . label ) . join ( separator ) ;
59
+ } ) ;
60
+ } ) ;
61
+
24
62
next ( ) ;
25
63
}
26
64
0 commit comments