Skip to content

Instantly share code, notes, and snippets.

@ioncreature
Created March 14, 2017 14:51
Show Gist options
  • Save ioncreature/eb5934e79349ecbb407de68b112a8896 to your computer and use it in GitHub Desktop.
Save ioncreature/eb5934e79349ecbb407de68b112a8896 to your computer and use it in GitHub Desktop.
TODO: rate of fire
'use strict';
class Fire {
/**
* @param {int} rate
*/
constructor(rate = 10) {
this.rate = rate;
this.isRunning = false;
}
set rate(value) {
if (!Number.isInteger(value) || value > 1e3 || value < 1)
throw new Error('rate should be integer between 1 and 1000');
this._rate = value;
}
get rate() {
return this._rate;
}
/**
* @param {Function} fn
*/
start(fn) {
if (this.isRunning)
return false;
this.isRunning = true;
this.ticksCount = 0;
this.ticksPerSec = 500;
this.fires = 0;
this.start = Date.now();
let run = () => {
if (!this.isRunning)
return;
let start = process.hrtime();
process.nextTick(() => {
this.ticksCount ++;
let count = this.getCount();
for (let i = 0; i < count; i++)
fn();
this.add(process.hrtime(start), count);
run();
});
};
run();
return true;
}
getCount() {
this.ticksCount ++;
let sinceStartOfSec = (Date.now() - this.start) % 1000 / 1000;
let haveToBeFired = Math.min(this.rate * sinceStartOfSec - (this.fires % this.rate), 10);
return (this.fires % this.rate) - this.rate * sinceStartOfSec;
let nthTick = this.ticksCount % this.ticksPerSec;
return Math.round(this.rate * nthTick);
}
stop() {
this.isRunning = false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment