import type { ICategoricalColumnDesc , ICategory } from '../../model' ; import ColumnBuilder from './ColumnBuilder' ; import { cleanCategories } from '../../provider/utils' ; import { resolveValue } from '../../internal' ; export default class CategoricalColumnBuilder extends ColumnBuilder < ICategoricalColumnDesc > { constructor ( column ) { super ( 'categorical' , column ) ; } /**
     * converts this type to an ordinal column type, such that categories are mapped to numbers
     */ asOrdinal ( ) { this . desc . type = 'ordinal' ; return this ; } param { ( string | Partial < ICategory > ) [ ] } categories categories ( categories ) { this . desc . categories = categories ; return this ; } param { string } separator asSet ( separator ? ) { if ( separator ) { ( this . desc as any ) . separator = separator ; } this . desc . type = 'set' ; return this ; } private derive ( data ) { const categories = new Set < string > ( ) ; const isSet = this . desc . type === 'set' ; const separator = ( this . desc as any ) . separator || ';' ; const val = ( vi ) => { if ( typeof vi === 'string' && vi !== '' ) { return vi ; } if ( vi != null && typeof vi . value === 'string' && vi . value !== '' ) { return vi . value ; } return null ; } ; const col = ( this . desc as any ) . column ; data . forEach ( ( d ) => { const v = resolveValue ( d , col ) ; if ( Array . isArray ( v ) ) { v . forEach ( ( vi ) => categories . add ( val ( vi ) ) ) ; } else if ( v != null && v !== '' ) { const vs = isSet ? [ v . toString ( ) ] : v . toString ( ) . split ( separator ) ; vs . forEach ( ( vi ) => categories . add ( val ( vi ) ) ) ; } } ) ; this . categories ( cleanCategories ( categories ) ) ; } build ( data ) { if ( ! this . desc . categories ) { this . derive ( data ) ; } return super . build ( data ) ; } } param { string } column param { ( string | Partial < ICategory > ) [ ] } categories returns { CategoricalColumnBuilder } export function buildCategoricalColumn ( column , categories ? ) { const r = new CategoricalColumnBuilder ( column ) ; if ( categories ) { r . categories ( categories ) ; } return r ; }