Percentage should work the same way as other math functions (round, floor,

etc) and throw error on NaN. #2553
This commit is contained in:
jurcovicovam
2015-07-20 14:31:53 +02:00
parent 3178103b7f
commit e8efa6e033
5 changed files with 34 additions and 18 deletions

View File

@@ -0,0 +1,16 @@
var Dimension = require("../tree/dimension");
var MathHelper = function() {
};
MathHelper._math = function (fn, unit, n) {
if (!(n instanceof Dimension)) {
throw { type: "Argument", message: "argument must be a number" };
}
if (unit == null) {
unit = n.unit;
} else {
n = n.unify();
}
return new Dimension(fn(parseFloat(n.value)), unit);
};
module.exports = MathHelper;

View File

@@ -1,5 +1,5 @@
var Dimension = require("../tree/dimension"),
functionRegistry = require("./function-registry");
var functionRegistry = require("./function-registry"),
mathHelper = require("./math-helper.js");
var mathFunctions = {
// name, unit
@@ -15,27 +15,15 @@ var mathFunctions = {
acos: "rad"
};
function _math(fn, unit, n) {
if (!(n instanceof Dimension)) {
throw { type: "Argument", message: "argument must be a number" };
}
if (unit == null) {
unit = n.unit;
} else {
n = n.unify();
}
return new Dimension(fn(parseFloat(n.value)), unit);
}
for (var f in mathFunctions) {
if (mathFunctions.hasOwnProperty(f)) {
mathFunctions[f] = _math.bind(null, Math[f], mathFunctions[f]);
mathFunctions[f] = mathHelper._math.bind(null, Math[f], mathFunctions[f]);
}
}
mathFunctions.round = function (n, f) {
var fraction = typeof f === "undefined" ? 0 : f.value;
return _math(function(num) { return num.toFixed(fraction); }, null, n);
return mathHelper._math(function(num) { return num.toFixed(fraction); }, null, n);
};
functionRegistry.addMultiple(mathFunctions);

View File

@@ -1,6 +1,7 @@
var Dimension = require("../tree/dimension"),
Anonymous = require("../tree/anonymous"),
functionRegistry = require("./function-registry");
functionRegistry = require("./function-registry"),
mathHelper = require("./math-helper.js");
var minMax = function (isMin, args) {
args = Array.prototype.slice.call(args);
@@ -71,6 +72,10 @@ functionRegistry.addMultiple({
return new Dimension(Math.pow(x.value, y.value), x.unit);
},
percentage: function (n) {
return new Dimension(n.value * 100, '%');
var result = mathHelper._math(function(num) {
return num * 100;
}, '%', n);
return result;
}
});

View File

@@ -0,0 +1,3 @@
div {
percentage: percentage(16/17);
}

View File

@@ -0,0 +1,4 @@
ArgumentError: error evaluating function `percentage`: argument must be a number in {path}percentage-non-number-argument.less on line 2, column 15:
1 div {
2 percentage: percentage(16/17);
3 }