I am currently working on sorting a list or array of file size strings in an intelligent manner, either in ascending or descending order. The string format consists of numbers (with or without decimals) followed by whitespace and then the unit.
For instance - ["5.1 GB", "19934563 B", "224 kB", "0.55 GB", "0.04 kB", "0.02 TB", "2.4 MB",], the expected result should be ["0.02 TB", "5.1 GB", "0.55 GB", "19934563 B", "2.4 MB", "224 kB", "0.04 kB"]
So far, this is my progress:
if (!fileSizes.length) return "Please enter a list to be sorted";
else {
//Checking the input format of strings
let validFormat = fileSizes.map((file) => validateFile(file));
if (validFormat.includes(false)) return "Invalid input format";
else {
let myfiles = reOrderFormat(fileSizes);
if (descending === true) {
sorter = MySort("TGMkB");
let mysortedFiles = myfiles.sort(sorter);
let result = reOrderFormat(mysortedFiles);
return result;
} else {
sorter = MySort("BkMGT");
let mysortedFiles = myfiles.sort(sorter);
let result = reOrderFormat(mysortedFiles);
return result;
}
}
}
}
//Helper Functions for validating input format
function validateFile(str) {
let regEx = /^(-?\d*(\.\d+)?)\s((T|G|M|k)*B)$/;
let valid = regEx.test(str);
return valid;
}
function validateList(arr) {
let validArray = arr.map((fileSiz) => validateFile(fileSiz));
return arr;
}
//Helper functions for sorting and reordering input format
function reOrderFormat(arr) {
let reOrdered = [];
arr.map((file) => {
let out = file.split(" ");
let first = out[1];
let second = out[0];
let newOrder = first + " " + second;
reOrdered.push(newOrder);
});
return reOrdered;
}
//Custom sorter function
function MySort(alphabet) {
return function (a, b) {
var index_a = alphabet.indexOf(a[0]),
index_b = alphabet.indexOf(b[0]);
if (index_a === index_b) {
if (a < b) {
return -1;
} else if (a > b) {
return 1;
}
return 0;
} else {
return index_a - index_b;
}
};
}
sort(
["5.1 GB", "19934563 B", "224 kB", "0.55 GB", "0.04 kB", "0.02 TB", "2.4 MB"],
true
);
The current implementation does not handle repeated units properly and may mix up long figures in bytes. I am looking for assistance in coding a more efficient solution.
Please provide any insights or suggestions you may have. Thank you.