Created
October 8, 2011 00:33
-
-
Save jhurliman/1271679 to your computer and use it in GitHub Desktop.
lockedStore.js
This file contains hidden or 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
LockedStore = function() { }; | |
LockedStore.prototype = { | |
table: [], | |
/** | |
* index - Index of the value to check out. | |
* callback(value, fn) - Fired when a lock is acquired on the requested value. First | |
* parameter is the requested value, second parameter is a callback that must be | |
* fired to check the value back in and expects the new value as a single parameter. | |
*/ | |
checkOut: function(index, callback) { | |
if (!this.table[index]) | |
this.table[index] = { locked: false, pending: [callback], data: null }; | |
var obj = this.table[index]; | |
if (obj.locked) | |
return obj.pending.push(callback); | |
var doCheckOut = function() { | |
obj.locked = true; | |
var curCallback = obj.pending.shift(); | |
curCallback(obj.data, function(newVal) { | |
obj.data = newVal; | |
obj.locked = false; | |
if (obj.pending.length) | |
doCheckOut(); | |
}); | |
}; | |
doCheckOut(); | |
}, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment