diff --git a/lib/utils.js b/lib/utils.js index 2cc0a0b..2df38af 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -255,7 +255,15 @@ var addCoreExtensions = function addCoreExtensions() { // // Returns an integer representing the scaled value Number.prototype.fromScale = function(start, end) { - return (this - Math.min(start, end)) / (Math.max(start, end) - Math.min(start, end)); + var val = (this - Math.min(start, end)) / (Math.max(start, end) - Math.min(start, end)); + + if (val > 1) { + val = 1; + } else if (val < 0){ + val = 0; + } + + return val; }; // Public: Convert value from (0..1) scale to new (start, end) scale diff --git a/test/specs/utils.spec.js b/test/specs/utils.spec.js index 1aeeb52..30733d4 100644 --- a/test/specs/utils.spec.js +++ b/test/specs/utils.spec.js @@ -25,6 +25,14 @@ describe("Utils", function() { it("converts floats", function() { expect(2.5.fromScale(0, 10)).to.be.eql(0.25); }); + + it("should return 1 if the number goes above the top of the scale", function() { + expect((15).fromScale(0, 10)).to.be.eql(1); + }); + + it("should return 0 if the number goes below the bottom of the scale", function() { + expect((5).fromScale(10, 20)).to.be.eql(0); + }); }); describe("#toScale", function() { @@ -32,6 +40,14 @@ describe("Utils", function() { expect((0.5).toScale(0, 10)).to.be.eql(5); }); + it("bottom of scale should be returned when value goes below it", function() { + expect((-5).toScale(0, 10)).to.be.eql(0); + }); + + it("top of scale should be returned when value goes above it", function() { + expect((15).toScale(0, 10)).to.be.eql(10); + }); + it("converts to floats", function() { expect(0.25.toScale(0, 10)).to.be.eql(2.5); });