Skip to content

Commit

Permalink
Fn: improved fmap
Browse files Browse the repository at this point in the history
Signed-off-by: Rick Waldron <waldron.rick@gmail.com>
  • Loading branch information
rwaldron committed Jul 21, 2016
1 parent 18ea9f3 commit 71ac3aa
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 9 deletions.
15 changes: 11 additions & 4 deletions lib/fn.js
Expand Up @@ -20,13 +20,17 @@ Fn.toFixed = function(number, digits) {
// Re-maps a number from one range to another.
// Based on arduino map()
//
// Return float
// Return Float32
//
var f32A = new Float32Array(1);

Fn.fmap = function(value, fromLow, fromHigh, toLow, toHigh) {
return (value - fromLow) * (toHigh - toLow) /
(fromHigh - fromLow) + toLow;
f32A[0] = (value - fromLow) * (toHigh - toLow) / (fromHigh - fromLow) + toLow;
return f32A[0];
};



// Alias
Fn.fscale = Fn.fmap;

Expand All @@ -37,8 +41,11 @@ Fn.fscale = Fn.fmap;
//
// Retun int
//
var s32A = new Int32Array(1);

Fn.map = function(value, fromLow, fromHigh, toLow, toHigh) {
return Fn.fmap(value, fromLow, fromHigh, toLow, toHigh) | 0;
s32A[0] = (value - fromLow) * (toHigh - toLow) / (fromHigh - fromLow) + toLow;
return s32A[0];
};

// Alias
Expand Down
7 changes: 2 additions & 5 deletions test/fn.js
Expand Up @@ -9,19 +9,16 @@ exports["Fn"] = {

map: function(test) {
test.expect(3);

test.equal(Fn.map(1009, 300, 1009, 0, 255), 255);
test.equal(Fn.map(300, 300, 1009, 0, 255), 0);
test.equal(Fn.map(500, 0, 1000, 0, 255), 127);

test.done();
},

fmap: function(test) {
test.expect(1);

test.expect(2);
test.equal(Fn.fmap(500, 0, 1000, 0, 255), 127.5);

test.equal(Fn.fmap(512, 0, 1023, 0, 255), 127.6246337890625);
test.done();
},

Expand Down

0 comments on commit 71ac3aa

Please sign in to comment.