Skip to content

Instantly share code, notes, and snippets.

@kareniel
Last active March 26, 2018 15:27
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 kareniel/06a68f340e5a71b2ae0cbf2a49e82084 to your computer and use it in GitHub Desktop.
Save kareniel/06a68f340e5a71b2ae0cbf2a49e82084 to your computer and use it in GitHub Desktop.
c# interfaces in js using mixins
// original idea from https://github.com/justinfagnani/mixwith.js
const _cachedApplications = '__cachedApplications';
class SuperClass ()
{
constructor (superclass)
{
return new MixinBuilder(superclass)
}
}
class MixinBuilder
{
constructor (superclass)
{
this.superclass = superclass || class {};
}
with (...mixins) {
return mixins.reduce((c, mixin) => mixin(c), this.superclass);
}
}
var DeDupe = (mixin) => wrap(mixin, (superclass) => (hasMixin(superclass.prototype, mixin))
? superclass
: mixin(superclass));
var Cached = (mixin) => wrap(mixin, (superclass) => {
var cachedApplications = superclass[_cachedApplications];
if (!cachedApplications) {
cachedApplications = superclass[_cachedApplications] = new Map();
}
var application = cachedApplications.get(mixin);
if (!application) {
application = mixin(superclass);
cachedApplications.set(mixin, application);
}
return application;
});
var BareMixin = (mixin) => wrap(mixin, (s) => apply(s, mixin));
var Mixin = mixin => DeDupe(Cached(BareMixin(mixin)));
var IActor = Mixin(superclass => class extends superclass () {
move (x, y)
{
this.position.x = x
this.position.y = y
}
})
class Person extends SuperClass().with(IActor)
{
constructor (name)
{
this.name = name
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment