Last active
February 12, 2023 13:10
-
-
Save ceving/b91c9e44b866126653c22ab147fd44f5 to your computer and use it in GitHub Desktop.
Mixin message passing in JavaScript
This file contains 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
function mapo (obj, proc) | |
{ | |
return Object.fromEntries(Object.entries(obj).map(proc)) | |
} | |
function mixin(mixture, condiment) | |
{ | |
for (const name in condiment) | |
Object.defineProperty(mixture, name, condiment[name]) | |
return mixture | |
} | |
function mixinv(mixture, condiment) | |
{ | |
return mixin(mixture, mapo(condiment, ([k, v]) => [k, {value: v}])) | |
} | |
function touchable(obj = Object.create({})) | |
{ | |
return mixinv(obj, { | |
reachables: [], | |
reactions: [], | |
reach: function (...rs) { | |
for (const r of rs) | |
this.reachables.push(r) | |
return this | |
}, | |
react: function (...rs) { | |
for (const r of rs) | |
this.reactions.push(r.bind(this)) | |
return this | |
}, | |
touch: function (...args) { | |
for (const react of this.reactions) | |
react(...args) | |
for (const reach of this.reachables) | |
reach.touch(...args) | |
}}) | |
} | |
class Person { | |
constructor(name) { | |
this.name = name | |
} | |
} | |
var f = touchable(new Person('father')) | |
var m = touchable(new Person('mother')) | |
var c = touchable(new Person('child')) | |
f.reach(m, c) | |
m.reach(c) | |
f.react(function (arg) { console.log(`${this.name}: ${arg}: wtf`) }) | |
m.react(function (arg) { console.log(`${this.name}: ${arg}: ouch`) }) | |
c.react(function (arg) { console.log(`${this.name}: ${arg}: cry`) }) | |
f.touch('pat') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment