import { IPipeFactory , PipeFactory } from './PipeFactory' ; import { IPipelineCompiler } from './IPipelineCompiler' ; export class PipelineCompiler implements IPipelineCompiler { constructor ( private readonly factory = new PipeFactory ( ) ) { } public compile ( value , pipeline ) { ensureValidArguments ( value , pipeline ) ; const pipeNames = extractPipeNames ( pipeline ) ; const pipes = pipeNames . map ( ( pipeName ) => this . factory . get ( pipeName ) ) ; return pipes . reduce ( ( previousValue , pipe ) => { return pipe . apply ( previousValue ) ; } , value ) ; } } function extractPipeNames ( pipeline ) { return pipeline . trim ( ) . split ( '|' ) . slice ( 1 ) . map ( ( p ) => p . trim ( ) ) ; } function ensureValidArguments ( value , pipeline ) { if ( ! value ) { throw new Error ( 'undefined value' ) ; } if ( ! pipeline ) { throw new Error ( 'undefined pipeline' ) ; } if ( ! pipeline . trimStart ( ) . startsWith ( '|' ) ) { throw new Error ( 'pipeline does not start with pipe' ) ; } }