> translate = new Interpolate();
-> val = translate.from(0, 5).to(0, 100).linear(2.5);
+> val = translate.from(0, 5).to(0, 100).val(2.5);
> console.assert(val === 50);
function Interpolate () {
+ this.input_from = null;
+ this.output_from = null;
Interpolate.prototype.from = function (min, max) {
- this.input_min = Number( min );
- this.input_max = Number( max );
+ this.input_from = Number( min );
+ this.input_to = Number( max );
-Interpolate.prototype.to = function (min, max) {
- this.output_min = Number( min );
- this.output_max = Number( max );
+Interpolate.prototype.to = function (_min, _max) {
+ y values (desired output range)
+ var min = Number( _min ),
+ this.output_from = min;
+ this.output_min = Math.min(min, max);
+ this.output_max = Math.max(min, max);
+Interpolate.prototype.checkBounds = function (output) {
+ check if value is between max/min
+ if (output > this.output_max) {
+ return this.output_max;
+ if (output < this.output_min) {
+ return this.output_min;
Interpolate.prototype.linear = function (val) {
- var output = (val - this.input_min) /
- (this.input_max - this.input_min) *
- (this.output_max - this.output_min) +
- if (output > this.output_max ||
- output < this.output_min) {
+ var output = (val - this.input_from) /
+ (this.input_to - this.input_from) *
+ (this.output_to - this.output_from) +
+ return this.checkBounds( output );
Interpolate.prototype.exponential = function (val) {
- x2 = this.input_max - this.input_min,
+ x2 = this.input_to - this.input_from,
- if (val === this.input_max) {
- return this.output_max;
+ if (val === this.input_to) {
- if (val === this.input_min) {
- return this.output_min;
+ if (val === this.input_from) {
+ return this.output_from;
// x is an index (starts at 0)
+ val -= this.input_from;
// can't have y = 0 or less for pow functions
// however, b is supposed to equal y
// when x == 0; so apparently this
// is a formula to find that
- b = Math.pow(y2 / y1, 1 / x2);
+ b = Math.pow(y2 / a, 1 / x2);
// formula here (reapply offset to deal with 0's)
output = a * Math.pow(b, val) - offset;
- if (output > this.output_max) {
- return this.output_max;
- if (output < this.output_min) {
- return this.output_min;
+ return this.checkBounds( output );