Skip to content

Instantly share code, notes, and snippets.

@dfkaye
Last active January 5, 2022 19:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dfkaye/c40384c320dbd9c6b966d45c2800aea3 to your computer and use it in GitHub Desktop.
Save dfkaye/c40384c320dbd9c6b966d45c2800aea3 to your computer and use it in GitHub Desktop.
Updated Dale Schumacher's "Actor Model in a Tweet" - and an async/await version
// 28 December 2020
// https://twitter.com/dfkaye/status/1343784103674400769
// Updated @dalnefre's actor model in a tweet:
var Actor = (a, e) => function c(b) {
a = d => setTimeout(() => b.call(e, d))
e = { self: a, behavior: b, sponsor: c }
return a
}
Actor()(s => console.log(s))("test")
// "test"
Actor()(s => console.log(this, s))("arrow scope")
// Window, "arrow scope"
Actor()(function(s) { console.log(this, s) })("function scope")
// Object{ self, behavior, sponsor }, "function scope"
/*
References:
https://twitter.com/dalnefre/status/407009429280669696
https://twitter.com/dalnefre/status/407887997003370496
http://dalnefre.com/wp/2014/03/actors-in-javascript/
*/
// 20 December 2021
// replace "setTimeout" with async/await on behavior b function
var A = (a, e) => function c(b) {
a = async d => await b.call(e, d)
e = { self: a, behavior: b, sponsor: c }
return a
}
A()(s => { console.log(s); return s })("example")
// logs "example"
// returns Promise { <state>: "fulfilled", <value>: "example" }
// 21 December 2021 - using fn.bind(console) logs but does not return the value.
A()(console.log.bind(console))("bound call")
// logs "bound call"
// returns Promise { <state>: "fulfilled", <value>: undefined }
// 21 December 2021 - using this? the behavior must be a function, not an arrow.
A()(s => { console.log(this); return s })("arrow")
// logs Window (global)
// returns Promise { <state>: "fulfilled", <value>: "arrow" }
A()(function(s) { console.log(this); return s })("function")
// logs Object { spec: asyn a(d), behavior: (s), sponsor: c(b, a, e) }
// returns Promise { <state>: "fulfilled", <value>: "function" }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment