Skip to content

Instantly share code, notes, and snippets.

@MightyPork
Created August 11, 2015 20:48
Show Gist options
  • Select an option

  • Save MightyPork/ba4e6d7fbdc9f2df7f69 to your computer and use it in GitHub Desktop.

Select an option

Save MightyPork/ba4e6d7fbdc9f2df7f69 to your computer and use it in GitHub Desktop.
TieredLock JS class
/**
* Tiered lock works as a multi-level boolean / mutex.
*
* Main use case is to disable page refresh during
* an ongoing task, when there can be multiple such tasks.
*/
function TieredLock() {
this._weight = 0;
this._locks = {};
}
/** Place a lock (optionally named) */
TieredLock.prototype.lock = function (name) {
if (typeof name == 'undefined') {
this._weight++;
} else {
// init if undefined
if (typeof this._locks[name] == 'undefined') {
this._locks[name] = 0;
}
this._locks[name]++;
}
};
/** Release a lock (plain or named) */
TieredLock.prototype.unlock = function (name) {
if (typeof name == 'undefined') {
// decrease, but don't go under zero.
if (this._weight > 0) {
this._weight--;
} else {
console.error('Lock underflow.');
}
} else {
if (this._locks[name] == 0) { // catch both zero & undefined
this._locks[name] = 0; // normalize to zero
console.error('Lock "' + name + '" underflow.');
return;
}
this._locks[name]--;
}
};
/** Check if the resource is locked - at least one lock active */
TieredLock.prototype.isLocked = function () {
if (this._weight > 0) return true;
for (var k in this._locks) {
if (this._locks.hasOwnProperty(k)) {
// if greater than zero, locked
if (this._locks[k]) {
return true;
}
}
}
return false;
};
/** Debug function - print status to console */
TieredLock.prototype.show = function () {
var named = '';
var first = true;
for (var k in this._locks) {
if (this._locks.hasOwnProperty(k)) {
var n = this._locks[k];
if (n > 0) {
if (!first) named += ', ';
named += k + ' ' + n + 'x';
first = false;
}
}
}
console.log('Locks: global ' + this._weight + 'x, named: ' + (first ? '<none>' : named));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment