Files
mixtape/zero.Web.UI/app/utils/strings.js
T
2021-09-15 10:40:02 +02:00

119 lines
2.4 KiB
JavaScript

import dayjs from 'dayjs';
const BYTE_UNIT = 'B';
const UNITS = ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const DATE_FORMAT = 'DD.MM.YY';
const TIME_FORMAT = 'HH:mm';
const DATETIME_FORMAT = DATE_FORMAT + ' ' + TIME_FORMAT;
export default {
/// <summary>
/// Generate a GUID
/// </summary>
guid(length)
{
var guid = ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
);
if (length > 0)
{
return guid.replace(/-/g, '').substring(0, length);
}
return guid;
},
/// <summary>
/// Generate human-readable filesize from byte number
/// </summary>
filesize(bytes)
{
if (typeof bytes !== 'number')
{
return '0 ' + BYTE_UNIT;
}
var thresh = 1024;
if (Math.abs(bytes) < thresh)
{
return bytes + ' ' + BYTE_UNIT;
}
var u = -1;
do
{
bytes /= thresh;
++u;
} while (Math.abs(bytes) >= thresh && u < UNITS.length - 1);
return bytes.toFixed(1) + ' ' + UNITS[u];
},
date(value, format)
{
if (!value)
{
return null;
}
format = format || DATE_FORMAT;
if (format === 'long')
{
format = DATETIME_FORMAT;
}
else if (format === 'short' || format === 'default')
{
format = DATE_FORMAT;
}
else if (format === 'time')
{
format = TIME_FORMAT;
}
return dayjs(value).format(format);
},
selectorToArray(selector)
{
if (!selector)
{
return selector;
}
selector = selector.replace(/\[(\w+)\]/g, '.$1');
selector = selector.replace(/^\./, '');
return selector.split('.');
},
currency(value, decimals, hideSymbol, noEncode)
{
if (isNaN(value))
{
value = 0;
}
var fixedDecimals = typeof decimals !== 'undefined';
decimals = !fixedDecimals ? 2 : decimals;
var hasDecimals = ~~value !== value;
var val = (hasDecimals || fixedDecimals) ? (value / 1).toFixed(decimals) : ~~value;
if (val === "-0." + "0".repeat(decimals))
{
val = "0." + "0".repeat(decimals);
}
return val.toString().replace(/\B(?=(\d{3})+(?!\d))/g, noEncode ? " " : "&nbsp;") + (hideSymbol === true ? "" : (noEncode ? " €" : "&nbsp;&euro;"));
// TODO we have dynamic currencies, not fixed to €
},
htmlToText(html)
{
let tag = document.createElement('div');
tag.innerHTML = html;
return tag.innerText;
}
};