Skip to content

Instantly share code, notes, and snippets.

@mathdoodle
Last active August 29, 2015 14:23
Show Gist options
  • Save mathdoodle/5cceefe9fcaa29f54e68 to your computer and use it in GitHub Desktop.
Save mathdoodle/5cceefe9fcaa29f54e68 to your computer and use it in GitHub Desktop.
Actors
{
"uuid": "a841f9a8-2141-43e3-85f2-3df8a44478b5",
"description": "Actors",
"dependencies": {},
"operatorOverloading": true
}
<!doctype html>
<html>
<head>
<style>
/* STYLE-MARKER */
</style>
<!-- SCRIPTS-MARKER -->
</head>
<body>
<script>
// CODE-MARKER
</script>
</body>
</html>
interface Actor {
behavior(message: Message): Message;
}
interface Message {
type: string;
}
interface Deposit extends Message {
amount: number;
}
function invokeAsync(callback) {
setTimeout(callback, 0);
}
/**
* Use this to send a message asynchronously to an object.
*/
function send(target: Actor, message: Message, callback: (err, message?: Message) => void) {
invokeAsync(function() {
try {
var response = target.behavior(message);
callback(void 0, response)
}
catch(e) {
callback(e)
}
})
}
class Account implements Actor {
private balance = 0;
behavior(message: Message): Message {
if (message.type === 'deposit') {
this.balance += message['amount'];
return {
type: 'balance',
value: this.balance
};
}
else {
throw new Error("Don't know how to handle " + message.type);
}
}
}
var account = new Account();
send(account, {type: 'deposit', amount: 100}, function(err, data) {
if (!err) {
console.log(JSON.stringify(data))
}
else {
console.log(err)
}
});
send(account, {type: 'deposit', amount: 50}, function(err, data) {
if (!err) {
console.log(JSON.stringify(data))
}
else {
console.log(err)
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment