vitess.io/vitess@v0.16.2/web/vtadmin/src/util/formatBytes.ts (about) 1 /** 2 * Copyright 2021 The Vitess Authors. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 const BASE = 1024; 18 const PRECISION = 2; 19 const UNITS = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']; 20 21 export const formatBytes = ( 22 bytes: number | Long | string | null | undefined, 23 units?: string | null | undefined 24 ): string | null => { 25 if (bytes === null || typeof bytes === 'undefined') return null; 26 27 const num = Number(bytes); 28 if (isNaN(num)) return null; 29 30 const i = units ? UNITS.indexOf(units) : Math.floor(Math.log(num) / Math.log(BASE)); 31 if (i < 0) return null; 32 33 return parseFloat((num / Math.pow(BASE, i)).toFixed(PRECISION)).toLocaleString() + ' ' + UNITS[i]; 34 };