Refactor formatBytes helper to use core units util

This commit is contained in:
Michael Lange 2021-03-25 21:55:55 -07:00
parent f6a377cd12
commit 285c9a9b50
3 changed files with 10 additions and 23 deletions

View File

@ -4,7 +4,7 @@ import { alias } from '@ember/object/computed';
import { inject as service } from '@ember/service';
import { tracked } from '@glimmer/tracking';
import classic from 'ember-classic-decorator';
import { reduceToLargestUnit } from 'nomad-ui/helpers/format-bytes';
import { reduceBytes } from 'nomad-ui/utils/units';
const sumAggregator = (sum, value) => sum + (value || 0);
@ -39,12 +39,12 @@ export default class TopologyControllers extends Controller {
@computed('totalMemory')
get totalMemoryFormatted() {
return reduceToLargestUnit(this.totalMemory)[0].toFixed(2);
return reduceBytes(this.totalMemory)[0].toFixed(2);
}
@computed('totalMemory')
get totalMemoryUnits() {
return reduceToLargestUnit(this.totalMemory)[1];
return reduceBytes(this.totalMemory)[1];
}
@computed('scheduledAllocations.@each.allocatedResources')
@ -86,7 +86,7 @@ export default class TopologyControllers extends Controller {
@computed('activeNode')
get nodeUtilization() {
const node = this.activeNode;
const [formattedMemory, memoryUnits] = reduceToLargestUnit(node.memory * 1024 * 1024);
const [formattedMemory, memoryUnits] = reduceBytes(node.memory * 1024 * 1024);
const totalReservedMemory = node.allocations.mapBy('memory').reduce(sumAggregator, 0);
const totalReservedCPU = node.allocations.mapBy('cpu').reduce(sumAggregator, 0);

View File

@ -1,6 +1,5 @@
import Helper from '@ember/component/helper';
const UNITS = ['Bytes', 'KiB', 'MiB', 'GiB'];
import { formatBytes } from 'nomad-ui/utils/units';
/**
* Bytes Formatter
@ -10,20 +9,8 @@ const UNITS = ['Bytes', 'KiB', 'MiB', 'GiB'];
* Outputs the bytes reduced to the largest supported unit size for which
* bytes is larger than one.
*/
export function reduceToLargestUnit(bytes) {
bytes || (bytes = 0);
let unitIndex = 0;
while (bytes >= 1024 && unitIndex < UNITS.length - 1) {
bytes /= 1024;
unitIndex++;
}
return [bytes, UNITS[unitIndex]];
function formatBytesHelper([bytes]) {
return formatBytes(bytes);
}
export function formatBytes([bytes]) {
const [number, unit] = reduceToLargestUnit(bytes);
return `${Math.floor(number)} ${unit}`;
}
export default Helper.helper(formatBytes);
export default Helper.helper(formatBytesHelper);

View File

@ -1,6 +1,6 @@
import d3Format from 'd3-format';
import { reduceToLargestUnit } from 'nomad-ui/helpers/format-bytes';
import { reduceBytes } from 'nomad-ui/utils/units';
const formatPercent = d3Format.format('+.0%');
const sumAggregate = (total, val) => total + val;
@ -90,7 +90,7 @@ class ResourceDiffs {
return '0 MiB';
}
const [memory, units] = reduceToLargestUnit(delta * 1024 * 1024);
const [memory, units] = reduceBytes(delta * 1024 * 1024);
const formattedMemory = Number.isInteger(memory) ? memory : memory.toFixed(2);
return `${formattedMemory} ${units}`;