changeset 32:4492db3b277e

Use human-readable file size units
author Guido Berhoerster <guido+feed-preview@berhoerster.name>
date Wed, 23 Jan 2019 14:53:28 +0100
parents 76e23b361e92
children d2bf40011989
files js/feed-preview.js
diffstat 1 files changed, 16 insertions(+), 1 deletions(-) [+]
line wrap: on
line diff
--- a/js/feed-preview.js	Tue Jan 22 14:40:06 2019 +0100
+++ b/js/feed-preview.js	Wed Jan 23 14:53:28 2019 +0100
@@ -8,6 +8,21 @@
 
 'use strict';
 
+function formatFileSize(size) {
+    const LIMITS_UNITS = new Map([
+        [1024 * 1024 * 1024, 'GiB'],
+        [1024 * 1024, 'MiB'],
+        [1024, 'KiB'],
+        [0, 'B']
+    ])
+    for (let [limit, unit] of LIMITS_UNITS) {
+        if (size >= limit) {
+            return `${Number(size / limit).toFixed(1)} ${unit}`;
+        }
+    }
+    return '? B';
+}
+
 export function renderFeedPreview(feedPreviewDocument, feed,
         expandEntriesByDefault) {
     // inject XSL stylesheet which transforms XHTML to HTML allowing the use of
@@ -122,7 +137,7 @@
                 fileLinkElement.textContent = file.filename;
 
                 fileNode.querySelector('.entry-file-info').textContent =
-                        `(${file.type}, ${file.size} bytes)`;
+                        `(${file.type}, ${ formatFileSize(file.size)})`;
 
                 fileListElement.appendChild(fileNode);
             }