-
Notifications
You must be signed in to change notification settings - Fork 929
/
Copy pathbytes.js
91 lines (75 loc) · 2.97 KB
/
bytes.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// numeral.js format configuration
// format : bytes
// author : Adam Draper : https://github.com/adamwdraper
(function (global, factory) {
if (typeof define === 'function' && define.amd) {
define(['../numeral'], factory);
} else if (typeof module === 'object' && module.exports) {
factory(require('../numeral'));
} else {
factory(global.numeral);
}
}(this, function (numeral) {
var decimal = {
base: 1000,
suffixes: ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
},
binary = {
base: 1024,
suffixes: ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']
};
var allSuffixes = decimal.suffixes.concat(binary.suffixes.filter(function (item) {
return decimal.suffixes.indexOf(item) < 0;
}));
var unformatRegex = allSuffixes.join('|');
// Allow support for BPS (http://www.investopedia.com/terms/b/basispoint.asp)
unformatRegex = '(' + unformatRegex.replace('B', 'B(?!PS)') + ')';
numeral.register('format', 'bytes', {
regexps: {
format: /([0\s]i?b)/,
unformat: new RegExp(unformatRegex)
},
format: function(value, format, roundingFunction) {
var output,
bytes = numeral._.includes(format, 'ib') ? binary : decimal,
suffix = numeral._.includes(format, ' b') || numeral._.includes(format, ' ib') ? ' ' : '',
power,
min,
max;
// check for space before
format = format.replace(/\s?i?b/, '');
for (power = 0; power <= bytes.suffixes.length; power++) {
min = Math.pow(bytes.base, power);
max = Math.pow(bytes.base, power + 1);
if (value === null || value === 0 || value >= min && value < max) {
suffix += bytes.suffixes[power];
if (min > 0) {
value = value / min;
}
break;
}
}
output = numeral._.numberToFormat(value, format, roundingFunction);
return output + suffix;
},
unformat: function(string) {
var value = numeral._.stringToNumber(string),
power,
bytesMultiplier;
if (value) {
for (power = decimal.suffixes.length - 1; power >= 0; power--) {
if (numeral._.includes(string, decimal.suffixes[power])) {
bytesMultiplier = Math.pow(decimal.base, power);
break;
}
if (numeral._.includes(string, binary.suffixes[power])) {
bytesMultiplier = Math.pow(binary.base, power);
break;
}
}
value *= (bytesMultiplier || 1);
}
return value;
}
});
}));