Show:
  1. /* Copyright © 2015-2016 David Valdman */
  2.  
  3. define(function(require, exports, module){
  4. var Stream = require('../streams/Stream');
  5. var OptionsManager = require('../core/OptionsManager');
  6.  
  7. /**
  8. * Differential is a Stream that emits differentials of consecutive
  9. * input values.
  10. *
  11. * It emits `start`, `update` and `end` events.
  12. *
  13. * @example
  14. *
  15. * var differential = new Differential();
  16. * // this gives differentials of mouse input
  17. * differential.subscribe(mouseInput.pluck('value'));
  18. *
  19. *
  20. * @class Differential
  21. * @extends Streams.Stream
  22. * @uses Core.OptionsManager
  23. * @namespace Streams
  24. * @constructor
  25. * @param [options] {Object} Options
  26. * @param [options.scale] {Number} Scale to apply to differential
  27. */
  28. function Differential(options){
  29. this.options = OptionsManager.setOptions(this, options);
  30.  
  31. var previous = undefined;
  32. var delta = undefined;
  33.  
  34. Stream.call(this, {
  35. update: function () { return delta; }
  36. });
  37.  
  38. this._eventInput.on('start', function (value) {
  39. if (value instanceof Array)
  40. previous = value.slice();
  41. else previous = value;
  42. });
  43.  
  44. this._eventInput.on('update', function (value) {
  45. var scale = this.options.scale;
  46. if (previous instanceof Array) {
  47. delta = [];
  48. for (var i = 0; i < previous.length; i++) {
  49. delta[i] = scale * (value[i] - previous[i]);
  50. previous[i] = value[i];
  51. }
  52. }
  53. else {
  54. delta = scale * (value - previous);
  55. previous = value;
  56. }
  57. }.bind(this));
  58. }
  59.  
  60. Differential.DEFAULT_OPTIONS = {
  61. scale : 1
  62. };
  63.  
  64. Differential.prototype = Object.create(Stream.prototype);
  65. Differential.prototype.constructor = Differential;
  66.  
  67. module.exports = Differential;
  68. });
  69.