/
CategoricalsColumn.ts
47 lines (38 loc) · 1.43 KB
/
CategoricalsColumn.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
import ArrayColumn, {IArrayColumnDesc} from './ArrayColumn';
import {ICategoricalDesc, ICategory, toCategories, toCategory} from './ICategoricalColumn';
import {IDataRow} from './interfaces';
export declare type ICategoricalsColumnDesc = ICategoricalDesc & IArrayColumnDesc<string | null>;
/**
* a string column with optional alignment
*/
export default class CategoricalsColumn extends ArrayColumn<string | null> {
readonly categories: ICategory[];
private readonly missingCategory: ICategory | null;
private readonly lookup = new Map<string, Readonly<ICategory>>();
constructor(id: string, desc: Readonly<ICategoricalsColumnDesc>) {
super(id, desc);
this.categories = toCategories(desc);
this.missingCategory = desc.missingCategory ? toCategory(desc.missingCategory, NaN) : null;
this.categories.forEach((d) => this.lookup.set(d.name, d));
}
getCategories(row: IDataRow) {
return super.getValues(row).map((v) => {
if (!v) {
return this.missingCategory;
}
const vs = String(v);
return this.lookup.has(vs) ? this.lookup.get(vs)! : this.missingCategory;
});
}
getSet(row: IDataRow) {
const r = new Set(this.getCategories(row));
r.delete(this.missingCategory);
return r;
}
getValues(row: IDataRow) {
return this.getCategories(row).map((v) => v ? v.name : null);
}
getLabels(row: IDataRow) {
return this.getCategories(row).map((v) => v ? v.label : '');
}
}