linear1.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. * @fileoverview A one dimensional linear interpolator.
  16. *
  17. */
  18. goog.provide('goog.math.interpolator.Linear1');
  19. goog.require('goog.array');
  20. goog.require('goog.asserts');
  21. goog.require('goog.math');
  22. goog.require('goog.math.interpolator.Interpolator1');
  23. /**
  24. * A one dimensional linear interpolator.
  25. * @implements {goog.math.interpolator.Interpolator1}
  26. * @constructor
  27. * @final
  28. */
  29. goog.math.interpolator.Linear1 = function() {
  30. /**
  31. * The abscissa of the data points.
  32. * @type {!Array<number>}
  33. * @private
  34. */
  35. this.x_ = [];
  36. /**
  37. * The ordinate of the data points.
  38. * @type {!Array<number>}
  39. * @private
  40. */
  41. this.y_ = [];
  42. };
  43. /** @override */
  44. goog.math.interpolator.Linear1.prototype.setData = function(x, y) {
  45. goog.asserts.assert(
  46. x.length == y.length,
  47. 'input arrays to setData should have the same length');
  48. if (x.length == 1) {
  49. this.x_ = [x[0], x[0] + 1];
  50. this.y_ = [y[0], y[0]];
  51. } else {
  52. this.x_ = x.slice();
  53. this.y_ = y.slice();
  54. }
  55. };
  56. /** @override */
  57. goog.math.interpolator.Linear1.prototype.interpolate = function(x) {
  58. var pos = goog.array.binarySearch(this.x_, x);
  59. if (pos < 0) {
  60. pos = -pos - 2;
  61. }
  62. pos = goog.math.clamp(pos, 0, this.x_.length - 2);
  63. var progress = (x - this.x_[pos]) / (this.x_[pos + 1] - this.x_[pos]);
  64. return goog.math.lerp(this.y_[pos], this.y_[pos + 1], progress);
  65. };
  66. /** @override */
  67. goog.math.interpolator.Linear1.prototype.getInverse = function() {
  68. var interpolator = new goog.math.interpolator.Linear1();
  69. interpolator.setData(this.y_, this.x_);
  70. return interpolator;
  71. };