Last active
March 26, 2018 15:27
-
-
Save kareniel/06a68f340e5a71b2ae0cbf2a49e82084 to your computer and use it in GitHub Desktop.
c# interfaces in js using mixins
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
// 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