Last active
December 21, 2015 08:58
-
-
Save seckcoder/6281530 to your computer and use it in GitHub Desktop.
limited access object
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
var assert = require("assert"), | |
ms = require("ms"); | |
function LimitedAccessObject(opts) { | |
var initial = { | |
times:1, | |
costed:0, | |
autoRefresh:false, | |
refreshInterval:0 | |
}; | |
for(var prop in initial) { | |
this[prop] = (opts[prop] === undefined ? initial[prop] : opts[prop]); | |
} | |
this.updateRefreshTime(); | |
} | |
LimitedAccessObject.prototype.updateRefreshTime = function () { | |
// use process.hrtime to reach high resolutions | |
this.refreshTime = process.hrtime(); | |
}; | |
LimitedAccessObject.prototype.needRefresh = function () { | |
if (this.autoRefresh) { | |
return true; | |
} else { | |
return false; | |
} | |
} | |
LimitedAccessObject.prototype.access = function() { | |
if (this.tryAccess()) { | |
this._access(); | |
return true; | |
} | |
return false; | |
} | |
LimitedAccessObject.prototype.tryAccess = function () { | |
if (this.costed >= this.times) { | |
if (!this.needRefresh()) { | |
// not auto refresh | |
return false; | |
} else if (this.canRefresh()) { | |
// we can refresh then continue; | |
this._refresh(); | |
return this.tryAccess(); | |
} else { | |
// auto refresh is set, but we cannot refresh it now. | |
return false; | |
} | |
} else { | |
// we can access | |
return true; | |
} | |
} | |
LimitedAccessObject.prototype._access = function () { | |
this.costed += 1; | |
} | |
LimitedAccessObject.prototype._refresh = function () { | |
this.updateRefreshTime(); | |
this.costed = 0; | |
} | |
LimitedAccessObject.prototype.untilLastRefreshInterval = function () { | |
var diff = process.hrtime(this.refreshTime); | |
return Math.floor(diff[0] * 1e3 + diff[1] / 1e6); | |
}; | |
LimitedAccessObject.prototype.canRefresh = function () { | |
// console.log(this.untilLastRefreshInterval()); | |
return this.untilLastRefreshInterval() >= this.refreshInterval; | |
} | |
module.exports = LimitedAccessObject; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment