Created
August 7, 2013 18:16
-
-
Save mudge/6176860 to your computer and use it in GitHub Desktop.
A work in progress.
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
/* go(function () { | |
* console.log('Foo'); | |
* }); | |
*/ | |
var go = function (f) { | |
if (typeof process.nextTick === 'function') { | |
process.nextTick(f); | |
} else if (typeof setImmediate === 'function') { | |
setImmediate(f); | |
} else { | |
setTimeout(f, 0); | |
} | |
} | |
/* select(c1, c2, c3, function (value, name) { | |
* console.log(name, value); | |
* }); | |
*/ | |
var select = function () { | |
var i, j, | |
options = [].slice.apply(arguments), | |
channels = options.slice(0, options.length - 1), | |
f = options[options.length - 1], | |
length = channels.length; | |
for (i = 0; i < length; i++) { | |
channels[i].receive(function f2 (value) { | |
for (j = 0; j < length; j++) { | |
if (i !== j) { | |
channels[j].unlisten(f2); | |
} | |
} | |
f(value); | |
}); | |
} | |
}; | |
var Channel = function (name) { | |
this.name = name; | |
this.listeners = []; | |
}; | |
Channel.prototype.receive = function (f) { | |
this.listeners.push(f); | |
}; | |
Channel.prototype.send = function (value) { | |
var listener = this.listeners.pop(); | |
listener(value, this.name); | |
}; | |
Channel.prototype.unlisten = function (listener) { | |
var idx = this.listeners.indexOf(listener); | |
if (idx > -1) { | |
this.listeners.splice(idx, 1); | |
} | |
}; | |
module.exports = { | |
go: go, | |
select: select, | |
Channel: Channel | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment