import { Pipe , PipeTransform , NgModule } from '@angular/core' ; import { isArray , isFunction , getProperty , CollectionPredicate } from '../utils/utils' ; @ Pipe ( { name : 'firstOrDefault' , } ) export class FirstOrDefaultPipe implements PipeTransform { private static find ( input , predicate , defaultValue ? ) { let found = false ; let result ; let i = - 1 ; while ( ! found && ++ i < input . length ) { found = predicate ( input [ i ] , i , input ) ; } if ( found ) { result = input [ i ] ; } if ( typeof result === 'undefined' && typeof defaultValue !== 'undefined' ) { result = defaultValue ; } return result ; } transform ( input , predicate , defaultValue ? ) { if ( ! isArray ( input ) ) { return input ; } if ( isFunction ( predicate ) ) { return FirstOrDefaultPipe . find ( input , < CollectionPredicate > predicate , defaultValue ) ; } else if ( isArray ( predicate ) ) { const [ key , value ] = < string [ ] > predicate ; return FirstOrDefaultPipe . find ( input , ( item ) => getProperty ( item , key ) === value , defaultValue ) ; } else if ( predicate ) { return FirstOrDefaultPipe . find ( input , item => item === < any > predicate , defaultValue ) ; } else { return input ; } } } @ NgModule ( { declarations : [ FirstOrDefaultPipe ] , exports : [ FirstOrDefaultPipe ] , } ) export class NgFirstOrDefaultPipeModule { }