@@ -4,17 +4,24 @@ import { Pipe, PipeTransform } from '@angular/core';
44 name : 'fileSize' ,
55} )
66export class FileSizePipe implements PipeTransform {
7- transform ( bytes : number ) : string {
8- if ( ! bytes ) {
9- return '' ;
10- } else if ( bytes < 1024 ) {
7+ private readonly SI_UNITS = [ 'B' , 'kB' , 'MB' , 'GB' , 'TB' , 'PB' , 'EB' , 'ZB' , 'YB' ] ;
8+ private readonly BINARY_UNITS = [ 'B' , 'KiB' , 'MiB' , 'GiB' , 'TiB' , 'PiB' , 'EiB' , 'ZiB' , 'YiB' ] ;
9+
10+ transform ( bytes : number | null | undefined , si = true ) : string {
11+ if ( bytes == null ) return '0 B' ;
12+
13+ const threshold = si ? 1000 : 1024 ;
14+ const units = si ? this . SI_UNITS : this . BINARY_UNITS ;
15+ const absBytes = Math . abs ( bytes ) ;
16+
17+ if ( absBytes < threshold ) {
1118 return `${ bytes } B` ;
12- } else if ( bytes < 1024 ** 2 ) {
13- return `${ ( bytes / 1024 ) . toFixed ( 1 ) } kB` ;
14- } else if ( bytes < 1024 ** 3 ) {
15- return `${ ( bytes / 1024 ** 2 ) . toFixed ( 1 ) } MB` ;
16- } else {
17- return `${ ( bytes / 1024 ** 3 ) . toFixed ( 1 ) } GB` ;
1819 }
20+
21+ const exponent = Math . min ( Math . floor ( Math . log ( absBytes ) / Math . log ( threshold ) ) , units . length - 1 ) ;
22+
23+ const value = bytes / Math . pow ( threshold , exponent ) ;
24+
25+ return `${ value . toFixed ( 1 ) } ${ units [ exponent ] } ` ;
1926 }
2027}
0 commit comments