/******************************************************************************** | |
* Copyright (c) 2015-2018 Contributors to the Eclipse Foundation | |
* | |
* See the NOTICE file(s) distributed with this work for additional | |
* information regarding copyright ownership. | |
* | |
* This program and the accompanying materials are made available under the | |
* terms of the Eclipse Public License v. 2.0 which is available at | |
* http://www.eclipse.org/legal/epl-2.0. | |
* | |
* SPDX-License-Identifier: EPL-2.0 | |
* | |
********************************************************************************/ | |
import { Pipe, PipeTransform } from '@angular/core'; | |
// this projects imports | |
import { FormatSize } from '../model/file-explorer.model'; | |
@Pipe({name: 'fileSize'}) | |
export class FileSizePipe implements PipeTransform { | |
constructor() {} | |
public transform(bytes: number | string, format?: FormatSize) { | |
let result = '-'; | |
if (typeof(bytes) === 'string') { | |
result = bytes; | |
} else { | |
if (bytes == undefined) { | |
result = '-'; | |
} | |
if (format == undefined) { | |
format = FormatSize.BINARY; | |
} | |
if (Math.abs(bytes) < format) { | |
result = bytes + ' B'; | |
} | |
let units: string[]; | |
switch (format) { | |
case FormatSize.DECIMAL: | |
units = ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; | |
break; | |
case FormatSize.BINARY: | |
units = ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']; | |
} | |
let u = -1; | |
do { | |
bytes /= format; | |
++u; | |
} while (Math.abs(bytes) >= format && u < units.length - 1); | |
result = bytes.toFixed(1) + ' ' + units[u]; | |
} | |
return result; | |
} | |
} |