Skip to content

Instantly share code, notes, and snippets.

@kleysonr
Forked from rwaldron/es5-sampler.js
Last active August 29, 2015 14:08
Show Gist options
  • Save kleysonr/c9ac08a267ddd41ed622 to your computer and use it in GitHub Desktop.
Save kleysonr/c9ac08a267ddd41ed622 to your computer and use it in GitHub Desktop.
// This version cannot protect its internal
// data from external tampering.
function Sampler(expect) {
this.values = new Array();
this.expect = expect;
}
Sampler.prototype.add = function(value) {
var length = this.values.length;
if (length === this.expect) {
this.values.shift();
}
this.values.push(value);
return this;
};
Sampler.prototype.average = function() {
var value = 0;
if (this.values.length === this.expect) {
for (var i = 0; i < this.expect; i++) {
value += this.values[i] | 0;
}
return Math.round(value / this.expect);
}
return null;
};
Sampler.prototype.reset = function() {
this.values.length = 0;
};
module.exports = Sampler;
let priv = new WeakMap();
export class Sampler {
constructor(expect) {
let list = new Array();
priv.set(this, { list, expect });
}
add(value) {
let stored = priv.get(this);
if (stored.list.length === stored.expect) {
stored.list.shift();
}
stored.list.push(value);
return this;
}
average() {
let stored = priv.get(this);
let value = 0;
if (stored.list.length === stored.expect) {
for (let n of stored.list) {
value += n | 0;
}
return Math.round(value / stored.expect);
}
return null;
}
reset() {
priv.get(this).list.length = 0;
}
}
var sampler = new Sampler(5);
sampler.add(10);
sampler.add(20);
sampler.add(15);
sampler.add(18);
sampler.add(19);
console.log(sampler.average() === 16);
sampler.reset();
sampler.add(0);
sampler.add(9);
sampler.add(18);
sampler.add(27);
sampler.add(36);
console.log(sampler.average() === 18);
sampler.reset();
sampler.add(1);
sampler.add(1);
sampler.add(1);
sampler.add(1);
sampler.add(1);
console.log(sampler.average() === 1);
sampler.reset();
sampler.add(2);
sampler.add(4);
sampler.add(6);
sampler.add(8);
sampler.add(10);
// This value will result in the first
// value (2) being shifted off.
sampler.add(1000);
console.log(sampler.average() === 206);
sampler.reset();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment