Permalink
Browse files

tools.parseUnitString and tools.parseAngle

  • Loading branch information...
1 parent 155597e commit d41ae38e709b1a8e94fe0d771620c3ec9db6b11c @iamdustan iamdustan committed Dec 5, 2012
Showing with 87 additions and 1 deletion.
  1. +41 −1 src/tools.js
  2. +46 −0 test/tools-spec.js
View
@@ -6,7 +6,8 @@ define([], function() {
noop = function() {},
push = [].push,
slice = [].slice,
- toString = {}.toString;
+ toString = {}.toString,
+ PI = Math.PI;
/**
*
@@ -339,6 +340,45 @@ define([], function() {
array.length -= numRemoved;
return array;
+ },
+
+ /**
+ * Parse a given unit string into the amount and unit
+ *
+ * @param {String} str The unit string. E.g. '90deg', '7em'
+ * @returns {Object} { amount, unit }
+ */
+ parseUnitString: function (str) {
+ var amount = parseFloat(str.match(/^\-?\d+/)),
+ unit = str.match(/[a-z]*$/i)[0];
+
+ return { amount: amount, unit: unit };
+ },
+
+ /**
+ * Parses the angle string to radians
+ * https://developer.mozilla.org/en-US/docs/CSS/angle
+ *
+ * @param {String} angle The angle/unit string
+ * @returns {Number} The angle in radians
+ */
+ parseAngle: function(angle) {
+ var parts = tools.parseUnitString(angle), unit = parts.amount, radians;
+
+ switch (parts.unit) {
+ case 'deg':
+ radians = unit * PI / 180; break;
+ case 'grad':
+ radians = unit * PI / 200; break;
+ case 'turn':
+ radians = unit * 2 * PI; break;
+ case 'rad':
+ radians = unit; break;
+ default:
+ return 0;
+ }
+
+ return radians;
}
};
View
@@ -284,4 +284,50 @@ define([
});
});
+ /*--------------------------------------------------------------------------*/
+
+ describe('tools.parseUnitString', function() {
+ var parseUnitString = tools.parseUnitString;
+
+ it('should return an amount and unit for a given unit string', function() {
+ var returned = parseUnitString('9deg');
+ var expected = { amount: 9, unit: 'deg' };
+
+ expect(returned).toEqual(expected);
+ });
+
+ it('should work with negative numbers', function() {
+ var returned = parseUnitString('-741232grad');
+ var expected = { amount: -741232, unit: 'grad' };
+
+ expect(returned).toEqual(expected);
+ });
+ });
+
+ describe('tools.parseAngle', function() {
+ var parseAngle = tools.parseAngle;
+
+ it('calculates radians for degrees', function() {
+ var calculated = parseAngle('45deg');
+ var expected = 0.7853981633974483;
+
+ expect(calculated).toBeCloseTo(expected, 10);
+ });
+
+ it('calculates radians for turns', function() {
+ var calculated = parseAngle('1turn');
+ var expected = 6.283185307179586;
+
+ expect(calculated).toBeCloseTo(expected, 10);
+ });
+
+ it('calculates radians for gradians', function () {
+ var calculated = parseAngle('-32grad');
+ var expected = -0.5026548245743669;
+
+ expect(calculated).toBeCloseTo(expected, 10);
+ });
+
+ });
+
});

0 comments on commit d41ae38

Please sign in to comment.