Merge pull request #2762 from nextcloud/add-js-computerFileSize

[downstream] Add js computer file size
This commit is contained in:
Lukas Reschke 2016-12-19 20:01:22 +01:00 committed by GitHub
commit 1287e624dd
2 changed files with 76 additions and 0 deletions

View file

@ -1668,6 +1668,52 @@ OC.Util = {
// TODO: remove original functions from global namespace
humanFileSize: humanFileSize,
/**
* Returns a file size in bytes from a humanly readable string
* Makes 2kB to 2048.
* Inspired by computerFileSize in helper.php
* @param {string} string file size in human readable format
* @return {number} or null if string could not be parsed
*
*
*/
computerFileSize: function (string) {
if (typeof string != 'string') {
return null;
}
var s = string.toLowerCase();
var bytes = parseFloat(s)
if (!isNaN(bytes) && isFinite(s)) {
return bytes;
}
var bytesArray = {
'b' : 1,
'k' : 1024,
'kb': 1024,
'mb': 1024 * 1024,
'm' : 1024 * 1024,
'gb': 1024 * 1024 * 1024,
'g' : 1024 * 1024 * 1024,
'tb': 1024 * 1024 * 1024 * 1024,
't' : 1024 * 1024 * 1024 * 1024,
'pb': 1024 * 1024 * 1024 * 1024 * 1024,
'p' : 1024 * 1024 * 1024 * 1024 * 1024
};
var matches = s.match(/([kmgtp]?b?)$/i);
if (matches[1]) {
bytes = bytes * bytesArray[matches[1]];
} else {
return null;
}
bytes = Math.round(bytes);
return bytes;
},
/**
* @param timestamp
* @param format

View file

@ -590,6 +590,36 @@ describe('Core base tests', function() {
}
});
});
describe('computerFileSize', function() {
it('correctly parses file sizes from a human readable formated string', function() {
var data = [
['125', 125],
['125.25', 125.25],
['0 B', 0],
['125 B', 125],
['125b', 125],
['125 KB', 128000],
['125kb', 128000],
['122.1 MB', 128031130],
['122.1mb', 128031130],
['119.2 GB', 127990025421],
['119.2gb', 127990025421],
['116.4 TB', 127983153473126],
['116.4tb', 127983153473126]
];
for (var i = 0; i < data.length; i++) {
expect(OC.Util.computerFileSize(data[i][0])).toEqual(data[i][1]);
}
});
it('returns null if the parameter is not a string', function() {
expect(OC.Util.computerFileSize(NaN)).toEqual(null);
expect(OC.Util.computerFileSize(125)).toEqual(null);
});
it('returns null if the string is unparsable', function() {
expect(OC.Util.computerFileSize('')).toEqual(null);
expect(OC.Util.computerFileSize('foobar')).toEqual(null);
});
});
describe('stripTime', function() {
it('strips time from dates', function() {
expect(OC.Util.stripTime(new Date(2014, 2, 24, 15, 4, 45, 24)))