Created
March 18, 2018 12:28
-
-
Save YonathanMeguira/3214f339d8b16f2d4f8c2c53e6a83053 to your computer and use it in GitHub Desktop.
fileSize pipe angular 5
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Pipe, PipeTransform } from '@angular/core'; | |
/* | |
* Convert bytes into largest possible unit. | |
* Takes an precision argument that defaults to 2. | |
* Usage: | |
* bytes | fileSize:precision | |
* Example: | |
* {{ 1024 | fileSize}} | |
* formats to: 1 KB | |
*/ | |
@Pipe({name: 'fileSize'}) | |
export class FileSizePipe implements PipeTransform { | |
private units = [ | |
'bytes', | |
'KB', | |
'MB', | |
'GB', | |
'TB', | |
'PB' | |
]; | |
transform(bytes: number = 0, precision: number = 2 ) : string { | |
if ( isNaN( parseFloat( String(bytes) )) || ! isFinite( bytes ) ) return '?'; | |
let unit = 0; | |
while ( bytes >= 1024 ) { | |
bytes /= 1024; | |
unit ++; | |
} | |
return bytes.toFixed( + precision ) + ' ' + this.units[ unit ]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment