Debian Codegraph @

closure-library/closure/goog/math/interpolator/linear1.js

raw
1 // Copyright 2012 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 /**
16 * @fileoverview A one dimensional linear interpolator.
17 *
18 */
19
20 goog.provide('goog.math.interpolator.Linear1');
21
22 goog.require('goog.array');
23 goog.require('goog.asserts');
24 goog.require('goog.math');
25 goog.require('goog.math.interpolator.Interpolator1');
26
27
28
29 /**
30 * A one dimensional linear interpolator.
31 * @implements {goog.math.interpolator.Interpolator1}
32 * @constructor
33 * @final
34 */
35 goog.math.interpolator.Linear1 = function() {
36 /**
37 * The abscissa of the data points.
38 * @type {!Array<number>}
39 * @private
40 */
41 this.x_ = [];
42
43 /**
44 * The ordinate of the data points.
45 * @type {!Array<number>}
46 * @private
47 */
48 this.y_ = [];
49 };
50
51
52 /** @override */
53 goog.math.interpolator.Linear1.prototype.setData = function(x, y) {
54 goog.asserts.assert(
55 x.length == y.length,
56 'input arrays to setData should have the same length');
57 if (x.length == 1) {
58 this.x_ = [x[0], x[0] + 1];
59 this.y_ = [y[0], y[0]];
60 } else {
61 this.x_ = x.slice();
62 this.y_ = y.slice();
63 }
64 };
65
66
67 /** @override */
68 goog.math.interpolator.Linear1.prototype.interpolate = function(x) {
69 var pos = goog.array.binarySearch(this.x_, x);
70 if (pos < 0) {
71 pos = -pos - 2;
72 }
73 pos = goog.math.clamp(pos, 0, this.x_.length - 2);
74
75 var progress = (x - this.x_[pos]) / (this.x_[pos + 1] - this.x_[pos]);
76 return goog.math.lerp(this.y_[pos], this.y_[pos + 1], progress);
77 };
78
79
80 /** @override */
81 goog.math.interpolator.Linear1.prototype.getInverse = function() {
82 var interpolator = new goog.math.interpolator.Linear1();
83 interpolator.setData(this.y_, this.x_);
84 return interpolator;
85 };