Created
December 4, 2012 10:38
-
-
Save demonixis/4202528 to your computer and use it in GitHub Desktop.
JavaScript Math helper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var MathHelper = { | |
// Get a value between two values | |
clamp: function (value, min, max) { | |
if (value < min) { | |
return min; | |
} | |
else if (value > max) { | |
return max; | |
} | |
return value; | |
}, | |
// Get the linear interpolation between two value | |
lerp: function (value1, value2, amount) { | |
amount = amount < 0 ? 0 : amount; | |
amount = amount > 1 ? 1 : amount; | |
return value1 + (value2 - value1) * amount; | |
} | |
}; |
@geowar1 Did you benchmark the Math.min(Math.max())
being faster? I'd be surprised if that was true.
The "if" method of clamp is ca. 4,5 times faster than the math min/max method.
Tested with chrome version 60.0.3112.90 64bit.
Benchmark:
Run the clamp function x-times (e.g. 1 000 000 000) with limits min 25% of range (x-times) and max 75%.
function runBench(func) {
console.log("Benchmark '" + func.name +"' running ...");
let value = 0;
let now = new Date().getTime();
let range = 1000000000;
let rangeMin = range * 0.25;
let rangeMax = range * 0.75;
for (let i = 0; i < range; i++) {
value = func(i, rangeMin, rangeMax);
}
console.log("Time: " + (new Date().getTime() - now) + " ms");
}
runBench(clamp1); // alternate with clamp2
If you run the benchmark tests sequentially the second test is always slower.
It's weird. The tests influence each other.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Another useful math routine is wrap:
Use it like this: