var Operation = require('operation/variadic')
function Signal () {
this._waiting = [[]]
this.occupied = false
this.open = null
if (arguments.length != 0) {
this.wait.apply(this, Array.prototype.slice.call(arguments))
}
}
Signal.prototype.wait = function () {
var vargs = Array.prototype.slice.call(arguments)
var timeout = typeof vargs[0] == 'number' ? vargs.shift() : null
var timer = null
var callback = Operation(vargs)
if (this.open == null) {
if (timeout != null) {
timer = setTimeout(this.notify.bind(this), timeout)
}
var cookie = {}
this.occupied = true
this._waiting[0].push({
cookie: cookie,
callback: callback,
timeout: timer
})
return cookie
}
callback.apply(null, this.open)
return null
}
Signal.prototype.cancel = function (cookie) {
var left = null
for (var i = 0, I = this._waiting.length; i < I; i++) {
for (var j = 0, J = this._waiting[i].length; j < J; j++) {
if (this._waiting[i][j].cookie === cookie) {
left = this._waiting[i].splice(j, 1).shift()
break
}
}
}
this.occupied = this._waiting.length != 0
if (left == null) {
return null
}
if (left.timeout != null) {
clearTimeout(left.timeout)
}
return left.callback
}