收集一些开发过程中精简短小实用的工具函数,每个函数如果有出处,会尽量标明可以做追溯。
function separate (num) {
const reg = /(?=(\B\d{3})+$)/g;
return String(num).replace(reg, ',');
}
function formatBytes(bytes, decimals = 2) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
出处:https://stackoverflow.com/questions/15900485/correct-way-to-convert-size-in-bytes-to-kb-mb-gb-in-javascript
function countDown () {
var deadline = 1898098000 // give a unix timestamp
var now = new Date().getTime()
var result = ''
setInterval(() => {
var t = deadline - now
var days = Math.floor(t / (1000 * 60 * 60 * 24))
var hours = Math.floor((t % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
var minutes = Math.floor((t % (1000 * 60 * 60)) / (1000 * 60))
var seconds = Math.floor((t % (1000 * 60)) / 1000)
if (t < 0) {
// clearInterval()
days = 0
hours = 0
minutes = 0
seconds = 0
}
result = days + 'days' + hours + 'h' + minutes + 'm' + seconds + 's'
}, 1000)