Permalink
Browse files

Simplify parseAngle and parseUnitString as per @basecode's advice

  • Loading branch information...
1 parent 518c54a commit d52839ea92c0f66c97c1d8c0be8043d1bd0932b5 @iamdustan iamdustan committed Dec 6, 2012
Showing with 26 additions and 15 deletions.
  1. +15 −12 src/tools.js
  2. +11 −3 test/tools-spec.js
View
@@ -345,35 +345,38 @@ define([], function() {
/**
* Parse a given unit string into the amount and unit
*
- * @param {String} str The unit string. E.g. '90deg', '7em'
- * @returns {Object} { amount, unit }
+ * @param {String} any The unit string. E.g. '90deg', '7em'
+ * @returns {String} unit
*/
- parseUnitString: function (str) {
- var amount = parseFloat(str),
- unit = str.match(/[a-z]*$/i)[0];
-
- return { amount: amount, unit: unit };
+ parseUnitString: function (any) {
+ // make sure it's a string and remove trailing whitespace
+ var unit = String(any).replace(/\s+$/, '');
+ // returns extracted unit or empty string
+ return unit.match(/[a-z]*$/i)[0];
},
/**
* Parses the angle string to radians
* https://developer.mozilla.org/en-US/docs/CSS/angle
*
- * @param {String} angle The angle/unit string
+ * @param {Number|String} angle The angle/unit string
* @returns {Number} The angle in radians
*/
parseAngle: function(angle) {
- var parts = tools.parseUnitString(angle), amount = parts.amount, radians;
+ var unit = tools.parseUnitString(angle),
+ amount = parseFloat(angle),
+ radians;
- switch (parts.unit) {
+ switch (unit) {
+ case '': // default
+ case 'rad':
+ radians = amount; break;
case 'deg':
radians = amount * PI / 180; break;
case 'grad':
radians = amount * PI / 200; break;
case 'turn':
radians = amount * 2 * PI; break;
- case 'rad':
- radians = amount; break;
default:
radians = 0;
}
View
@@ -289,19 +289,27 @@ define([
describe('tools.parseUnitString', function() {
var parseUnitString = tools.parseUnitString;
- it('should return an amount and unit for a given unit string', function() {
+ it('return the unit from a unit string', function() {
var returned = parseUnitString('9deg');
- var expected = { amount: 9, unit: 'deg' };
+ var expected = 'deg';
expect(returned).toEqual(expected);
});
it('should work with negative numbers', function() {
var returned = parseUnitString('-741232grad');
- var expected = { amount: -741232, unit: 'grad' };
+ var expected = 'grad';
expect(returned).toEqual(expected);
});
+
+ it('should work with trailing whitespace', function() {
+ var returned = parseUnitString('-741232grad ');
+ var expected = 'grad';
+
+ expect(returned).toEqual(expected);
+ });
+
});
describe('tools.parseAngle', function() {

0 comments on commit d52839e

Please sign in to comment.