From b43566898ce6eab18ed8d8c36d44e4dbeb7624d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20Strau=C3=9F?= Date: Tue, 16 Jan 2018 14:51:38 +0100 Subject: [PATCH] feat(math): mapRange --- src/math/math.js | 17 +++++++++++++++++ test/math/math_spec.js | 22 ++++++++++++++++++++++ test/test_main.js | 2 ++ 3 files changed, 41 insertions(+) create mode 100644 src/math/math.js create mode 100644 test/math/math_spec.js diff --git a/src/math/math.js b/src/math/math.js new file mode 100644 index 0000000..eacbba0 --- /dev/null +++ b/src/math/math.js @@ -0,0 +1,17 @@ +goog.module('clulib.math'); + +/** + * Maps a value from one range to another range. + * + * @param {number} x + * @param {number} inMin + * @param {number} inMax + * @param {number} outMin + * @param {number} outMax + * @returns {number} + */ +function mapRange (x, inMin, inMax, outMin, outMax) { + return (x - inMin) * (outMax - outMin) / (inMax - inMin) + outMin; +} + +exports = {mapRange}; diff --git a/test/math/math_spec.js b/test/math/math_spec.js new file mode 100644 index 0000000..796f9da --- /dev/null +++ b/test/math/math_spec.js @@ -0,0 +1,22 @@ +goog.module('test.clulib.math'); + +const {mapRange} = goog.require('clulib.math'); + +exports = function () { + describe('clulib.math', () => { + describe('mapRange', () => { + it('should map a value from one range to another range', () => { + expect(mapRange(1, 0, 10, 0, 100)).toBe(10); + expect(mapRange(5, 0, 10, 0, 100)).toBe(50); + + expect(mapRange(11, 0, 10, 0, 100)).toBe(110); + expect(mapRange(15, 0, 10, 0, 100)).toBe(150); + + expect(mapRange(-1, 0, 10, 0, 100)).toBe(-10); + expect(mapRange(-5, 0, 10, 0, 100)).toBe(-50); + + expect(mapRange(-5, -10, 0, -100, 0)).toBe(-50); + }); + }); + }); +}; diff --git a/test/test_main.js b/test/test_main.js index 821cb97..0375477 100644 --- a/test/test_main.js +++ b/test/test_main.js @@ -6,6 +6,7 @@ const cmMain = goog.require('test.clulib.cm'); const domMain = goog.require('test.clulib.dom'); const functionsMain = goog.require('test.clulib.functions'); const httpRequestMain = goog.require('test.clulib.net.http_request'); +const mathMain = goog.require('test.clulib.math'); arrayMain(); asyncCompleterMain(); @@ -13,3 +14,4 @@ cmMain(); domMain(); functionsMain(); httpRequestMain(); +mathMain();