Skip to content

Instantly share code, notes, and snippets.

@599316527
Created October 30, 2015 15:08
Show Gist options
  • Save 599316527/a0d1300630baa4f82aa1 to your computer and use it in GitHub Desktop.
Save 599316527/a0d1300630baa4f82aa1 to your computer and use it in GitHub Desktop.
Smart File Size Filter for VueJS
var Vue = require('vue');
var UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
var STEP = 1024;
function format(value, power) {
return (value / Math.pow(STEP, power)).toFixed(2) + UNITS[power];
}
Vue.filter('smart-file-size', {
read: function (value) {
value = parseFloat(value, 10);
for (var i = 0; i < UNITS.length; i++) {
if (value < Math.pow(STEP, i)) {
if (UNITS[i - 1]) {
return format(value, i - 1);
}
return value + UNITS[i];
}
}
return format(value, i - 1);
},
write: function (value, oldValue) {
var exp = new RegExp('^(\\d+(?:\\.\\d+)?)(' + UNITS.join('|') +')$', 'i');
var ret = value.match(exp);
if (ret) {
var i = UNITS.indexOf(ret[2].toUpperCase());
if (i >= 0) {
return parseFloat(ret[1], 10) * Math.pow(STEP, i);
}
}
return oldValue;
}
});
@cldwrxsarv
Copy link

i is not defined in line 21

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment