t-comm
Version:
专业、稳定、纯粹的工具库
60 lines (58 loc) • 1.76 kB
JavaScript
var HEX_INT_MAP = {
A: 10,
B: 11,
C: 12,
D: 13,
E: 14,
F: 15
};
var INT_HEX_MAP = {
10: 'A',
11: 'B',
12: 'C',
13: 'D',
14: 'E',
15: 'F'
};
var isOnePointZero = function isOnePointZero(n) {
return typeof n === 'string' && n.indexOf('.') !== -1 && parseFloat(n) === 1;
};
var isPercentage = function isPercentage(n) {
return typeof n === 'string' && n.indexOf('%') !== -1;
};
// Take input from [0, n] and return it as [0, 1]
var bound01 = function bound01(value, max) {
if (isOnePointZero(value)) value = '100%';
var processPercent = isPercentage(value);
value = Math.min(max, Math.max(0, parseFloat(value)));
// Automatically convert percentage into number
if (processPercent) {
value = parseInt("".concat(value * max), 10) / 100;
}
// Handle floating point rounding errors
if (Math.abs(value - max) < 0.000001) {
return 1;
}
// Convert into [0, 1] range if it isn't already
return value % max / parseFloat("".concat(max));
};
var parseHexChannel = function parseHexChannel(hex) {
if (hex.length === 2) {
return (HEX_INT_MAP[hex[0].toUpperCase()] || +hex[0]) * 16 + (HEX_INT_MAP[hex[1].toUpperCase()] || +hex[1]);
}
return HEX_INT_MAP[hex[0].toUpperCase()] || +hex[0];
};
var rgbToHex = function rgbToHex(_a) {
var r = _a.r,
g = _a.g,
b = _a.b;
var hexOne = function hexOne(value) {
value = Math.min(Math.round(value), 255);
var high = Math.floor(value / 16);
var low = value % 16;
return "".concat(INT_HEX_MAP[high] || high).concat(INT_HEX_MAP[low] || low);
};
if (isNaN(r) || isNaN(g) || isNaN(b)) return '';
return "#".concat(hexOne(r)).concat(hexOne(g)).concat(hexOne(b));
};
export { bound01, isOnePointZero, isPercentage, parseHexChannel, rgbToHex };