Created
March 14, 2017 14:51
-
-
Save ioncreature/eb5934e79349ecbb407de68b112a8896 to your computer and use it in GitHub Desktop.
TODO: rate of fire
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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