-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProportionNormalizer.ts
62 lines (55 loc) · 2.25 KB
/
ProportionNormalizer.ts
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
import _ = require('lodash');
import Utils = require('../calculators/Utils');
class ProportionNormalizer {
static getLabelMatchingAbbreviation(normalizedLabel: string, abbreviations: Mapping): string | null {
const matchingAbbreviation = _.find(
_.keys(abbreviations),
(abbreviation) =>
abbreviation === normalizedLabel ||
new RegExp(`^${abbreviation}[- ]`).test(normalizedLabel) ||
new RegExp(`[- ]${abbreviation}$`).test(normalizedLabel)
);
return matchingAbbreviation ? abbreviations[matchingAbbreviation] : null;
}
normalize(proportions: Proportion[], totalWithValue: number, valueMappings: NormalizerMappings): Proportion[] {
const mergedLabels: { [label: string]: boolean } = {};
const { aliases, abbreviations } = valueMappings;
return _.chain(proportions)
.map((proportion, proportionIndex) => {
// Ignore merged proportions
if (mergedLabels[proportion.label]) {
return null;
}
// Ignore unknown values
if (proportion.label === '') {
return null;
}
// Add following proportions' values that should be merged to current proportion's value
const normalizedLabel = proportion.label.toLowerCase();
const followingProportions = _.drop(proportions, proportionIndex + 1);
const normalizedCount = followingProportions.reduce((currentCount, followingProportion) => {
const normalizedFollowingLabel = followingProportion.label.toLowerCase();
if (
aliases[normalizedFollowingLabel] === normalizedLabel ||
normalizedFollowingLabel.includes(normalizedLabel) ||
ProportionNormalizer.getLabelMatchingAbbreviation(normalizedFollowingLabel, abbreviations) ===
normalizedLabel
) {
mergedLabels[followingProportion.label] = true;
return currentCount + followingProportion.count;
}
return currentCount;
}, proportion.count);
return {
...proportion,
count: normalizedCount,
percentage: Utils.renderPercentage(normalizedCount, totalWithValue),
};
})
.compact()
.sortBy('count')
.reverse()
.value();
}
}
export = ProportionNormalizer;