css-math
Version:
Simple library for performing math operations on CSS properties
102 lines (83 loc) • 2.53 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
var allowedUnits = ['%', 'px', 'rem', 'em'];
/**
* Check the value doesn't contain anything bad by removing all allowed items
*
* @param value
* @return bool
*/
var check = function check(value) {
var sanitised = allowedUnits.reduce(function (newValue, unit) {
return newValue.replace(new RegExp('([0-9.]*)' + unit, 'gi'), '$1');
}, value);
// remove all the numbers
sanitised = sanitised.replace(/[0-9]/g, '');
// remove all operators, brackets, spaces and dots
sanitised = ['+', '-', '*', '/', '(', ')', '.', ' '].reduce(function (newValue, unit) {
return newValue.split(unit).join('');
}, sanitised);
if (sanitised.length) {
// console.warn('Invalid value passed to parser: ', value);
return false;
}
return true;
};
/**
* Parse the value and return
*
* @param value
* @param decimalPlaces Max number of decimal places to return, 6 seems ok for most browsers
*/
var parse = function parse(value) {
var decimalPlaces = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 6;
try {
// check the value
if (check(value)) {
// execute and return the value
var calculatedValue = new Function("return " + value)();
// round and return
return decimalPlaces ? +calculatedValue.toFixed(decimalPlaces) : calculatedValue;
}
} catch (err) {
console.warn('css-math parse() failed', value);
}
// something went wrong
return 0;
};
/**
* Find the unit of the item
*
* @param cssValue
* @return {}
*/
var findAndReplaceUnits = exports.findAndReplaceUnits = function findAndReplaceUnits(cssValue) {
return allowedUnits.reduce(function (result, value) {
if (result.value.indexOf(value) !== -1) {
// found a unit
return result = {
value: String(result.value.replace(new RegExp('([0-9.]*)' + value, 'gi'), '$1')),
unit: value
};
}
return result;
}, { value: String(cssValue), unit: '' });
};
/**
* Parse the value
*
* @param cssValue
* @returns {string}
*/
exports.default = function (cssValue) {
// find the units in the string and remove them
var _findAndReplaceUnits = findAndReplaceUnits(cssValue),
value = _findAndReplaceUnits.value,
unit = _findAndReplaceUnits.unit;
// parse the value
var parsedValue = parse(value);
// return the parsed value and it's unit if one existed
return parsedValue && unit ? '' + parsedValue + unit : parsedValue;
};