Created
October 30, 2015 15:08
-
-
Save 599316527/a0d1300630baa4f82aa1 to your computer and use it in GitHub Desktop.
Smart File Size Filter for VueJS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
i is not defined in line 21