Created
February 25, 2019 06:05
-
-
Save chrisengelsma/cef1a89268a2be01ce7027100912891a to your computer and use it in GitHub Desktop.
Angular2+ Pipe to format bytes to human-legible units
This file contains 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 } from '@angular/core'; | |
/** | |
* Formats a byte value to a human-readable format. | |
* | |
* Example uses: | |
* ------------- | |
* {{ value | formatBytes }} - use short units. | |
* {{ value | formatBytes: "long"}} - use long name units | |
*/ | |
@Pipe({ | |
name: 'formatBytes', | |
pure: false | |
}) | |
export class FormatBytesPipe { | |
private _units: string[] = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'YB']; | |
private _unitsLong: string[] = [ 'Bytes', 'Kilobytes', 'Megabytes', 'Gigabytes', 'Terabytes', 'Pedabytes', 'Yottabytes']; | |
constructor() { } | |
transform(bytes: any, format: string): any { | |
if (!Number(bytes)) { return ''; } | |
let units: string[]; | |
if (format === 'long') { | |
units = this._unitsLong; | |
} else { | |
units = this._units; | |
} | |
bytes = Math.max(bytes, 0); | |
let pow = Math.floor((bytes ? Math.log(bytes) : 0) / Math.log(1024)); | |
pow = Math.min(pow, this._units.length - 1); | |
const value = bytes / (Math.pow(1000, pow)); | |
return value + " " + units[pow]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks 👍 But you should use pure: true and format = 'short' in params to use short form without second parameter