import moment from 'moment' ; import { AnomalyRecordDoc } from '../../../common/types/anomalies' ; const SIGFIGS_IF_ROUNDING = 3 ; export function formatValue ( value , mlFunction , fieldFormat ? , record ? ) { if ( Array . isArray ( value ) ) { if ( value . length === 1 ) { return formatSingleValue ( value [ 0 ] , mlFunction , fieldFormat , record ) ; } else { const values = value . map ( ( val ) => formatSingleValue ( val , mlFunction , undefined , record ) ) ; return `[${ values }]` ; } } else { return formatSingleValue ( value , mlFunction , fieldFormat , record ) ; } } export function formatSingleValue ( value , mlFunction ? , fieldFormat ? , record ? ) { if ( value === undefined || value === null ) { return '' ; } if ( mlFunction === 'time_of_week' ) { const d = record !== undefined && record . timestamp !== undefined ? new Date ( record . timestamp ) : new Date ( ) ; const utcMoment = moment . utc ( d ) . startOf ( 'week' ) . add ( value , 's' ) ; return moment ( utcMoment . valueOf ( ) ) . format ( 'ddd HH:mm' ) ; } else if ( mlFunction === 'time_of_day' ) { const d = record !== undefined && record . timestamp !== undefined ? new Date ( record . timestamp ) : new Date ( ) ; const utcMoment = moment . utc ( d ) . startOf ( 'day' ) . add ( value , 's' ) ; return moment ( utcMoment . valueOf ( ) ) . format ( 'HH:mm' ) ; } else { if ( fieldFormat !== undefined ) { return fieldFormat . convert ( value , 'text' ) ; } else { const absValue = Math . abs ( value ) ; if ( absValue >= 10000 || absValue === Math . floor ( absValue ) ) { if ( fieldFormat !== undefined ) { return fieldFormat . convert ( value , 'text' ) ; } else { return Number ( value . toFixed ( 0 ) ) ; } } else if ( absValue >= 10 ) { return Number ( value . toFixed ( 1 ) ) ; } else { let multiple ; if ( value > 0 ) { multiple = Math . pow ( 10 , SIGFIGS_IF_ROUNDING - Math . floor ( Math . log ( value ) / Math . LN10 ) - 1 ) ; } else { multiple = Math . pow ( 10 , SIGFIGS_IF_ROUNDING - Math . floor ( Math . log ( - 1 * value ) / Math . LN10 ) - 1 ) ; } return Math . round ( value * multiple ) / multiple ; } } } }