import { isNotNil , isFunction } from '@terascope/utils' ; import { FieldTransformConfig , InitialFunctionContext , FunctionContext } from '../../../../function-configs/interfaces' ; import { callValue } from '../../utils' ; import { DynamicFunctionAdapterContext , FunctionAdapterContext } from '../../interfaces' ; import { validateFunctionArgs } from '../../../argument-validator' ; export function fieldTransformColumnExecution < T extends Record < string , any > = Record < string , unknown > > ( fnDef , configs ) { return function _fieldTransformColumnExecution ( input ) : ( unknown | null ) [ ] { if ( ! Array . isArray ( input ) ) { throw new Error ( 'Invalid input, expected an array of values' ) ; } if ( isFunction ( configs . args ) ) { const dynamicContext = { ... configs , parent : input , } as DynamicFunctionAdapterContext < T > ; return _processesTransformDynamic < T > ( fnDef , dynamicContext ) ; } const functionContext = { ... configs , args : configs . args as T , parent : input } ; return _processesTransform < T > ( fnDef , functionContext ) ; } ; } function _processesTransform < T > ( fnDef , configs ) { const fn = fnDef . create ( configs ) ; const input = configs . parent as unknown [ ] ; const results = [ ] ; for ( let i = 0 ; i < input . length ; i ++ ) { const value = input [ i ] ; _processFieldTransform ( fn , value , configs . preserveNulls , i , results ) ; } return results ; } function _processesTransformDynamic < T > ( fnDef , configs ) { const results = [ ] ; const input = configs . parent ; for ( let i = 0 ; i < input . length ; i ++ ) { const newArgs = configs . args ( i ) as T ; validateFunctionArgs ( fnDef , newArgs ) ; const fnConfig = { ... configs , args : newArgs as T , } ; const fn = fnDef . create ( fnConfig ) ; const value = input [ i ] ; _processFieldTransform ( fn , value , configs . preserveNulls , i , results ) ; } return results ; } function _processFieldTransform ( fn , value , preserveNulls , i , results ) { if ( isNotNil ( value ) ) { if ( Array . isArray ( value ) ) { const fieldList = callValue ( fn , value , preserveNulls , false , i ) ; if ( fieldList . length > 0 ) { results . push ( fieldList ) ; } else if ( preserveNulls ) { results . push ( null ) ; } } else { const newValue = callValue ( fn , value , preserveNulls , false , i ) ; results . push ( ... newValue ) ; } } else if ( preserveNulls ) { results . push ( null ) ; } }