Skip to content

Instantly share code, notes, and snippets.

@lamjar
Forked from JonCatmull/file-size.pipe.ts
Created January 31, 2018 14:54
Show Gist options
  • Save lamjar/8efdd7a3f47d9c67d4854f4569127b1e to your computer and use it in GitHub Desktop.
Save lamjar/8efdd7a3f47d9c67d4854f4569127b1e to your computer and use it in GitHub Desktop.
Angular2 + TypeScript file size Pipe/Filter. Convert bytes into largest possible unit. e.g. 1024 => 1 KB
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