×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Javascript
Posted by: Isaac Dettman
Added: Nov 26, 2016 5:59 PM
Views: 4
Fixed Length Array
  1. module.exports = FixedValueHistory
  2.  
  3. // A fixed-length storage mechanism for a value (ideally a number)
  4. // with some statistics methods. Expires oldest values to
  5. // Input is not type checked, but non-numeric input will be considered NULL
  6. // WRT the statistical methods.
  7. function FixedValueHistory(maxLength, initial) {
  8.   if (!(this instanceof FixedValueHistory))
  9.     return new FixedValueHistory(maxLength, initial)
  10.   if (!isNumber(maxLength) || maxLength == 0) {
  11.     throw new Error("maxLength must be a positive number.")
  12.   }
  13.   this.maxLength = Math.floor(+maxLength)
  14.   if (initial != null) {
  15.     this.push(initial)
  16.   }
  17. }
  18. FixedValueHistory.prototype.sum = 0
  19. FixedValueHistory.prototype.maxLength = undefined
  20. FixedValueHistory.prototype.array = []
  21.  
  22. FixedValueHistory.prototype.push = function (vals) {
  23.   this.array = this.array.concat(vals)
  24.   var expired = this.array.splice(0, this.array.length - this.maxLength)
  25.   var expired_sum = FixedValueHistory.sum(expired)
  26.   this.sum -= expired_sum
  27.   var new_sum = FixedValueHistory.sum(vals)
  28.   this.sum += new_sum
  29. }
  30. FixedValueHistory.prototype.mean = function () {
  31.   if (this.array.length === 0) return NaN
  32.   return this.sum / this.array.length
  33. }
  34. FixedValueHistory.prototype.variance = function () {
  35.   if (this.array.length === 0) return NaN
  36.   var mean = this.mean()
  37.   return this.array.reduce(function(prevVal,currVal) {
  38.       var diff
  39.       if(isNumber(currVal)) {
  40.           diff = currVal - mean
  41.       } else {
  42.           diff = mean
  43.       }
  44.       return prevVal + diff*diff
  45.   }, 0) / this.array.length
  46. }
  47. FixedValueHistory.prototype.max = function () {
  48.   if (this.array.length === 0) return NaN
  49.   return Math.max.apply(null, this.array)
  50. }
  51. FixedValueHistory.prototype.min = function () {
  52.   if (this.array.length === 0) return NaN
  53.   return Math.min.apply(null, this.array)
  54. }
  55. FixedValueHistory.prototype.length = function () {
  56.   return this.array.length
  57. }
  58. FixedValueHistory.prototype.values = function () {
  59.   return this.array.slice(0)
  60. }
  61.  
  62. // Static methods.
  63. FixedValueHistory.sum = function (vals) {
  64.   var sum = 0
  65.   ;[].concat(vals).forEach(function (n) {
  66.     if (isNumber(n)) {
  67.       sum += n
  68.     }
  69.   })
  70.   return sum
  71. }
  72.  
  73. function isNumber(n) {
  74.   return !isNaN(parseFloat(n)) && isFinite(n)
  75. }