Created
November 22, 2017 13:26
-
-
Save Oikio/16c33fdfc6f0d99a212fd10fe84b5143 to your computer and use it in GitHub Desktop.
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
let _id = 0 | |
const id = () => { | |
_id++ | |
return _id | |
} | |
type Entity<Components = {}, Methods = {}> = { | |
id: number | |
} & Components & | |
Methods | |
interface NameComponent { | |
name: string | |
} | |
interface WithName { | |
components: { name: NameComponent } | |
} | |
const nameComponent = (name: string): NameComponent => { | |
return { name } | |
} | |
interface JumpComponent { | |
power: number | |
} | |
interface WithJump { | |
components: { jump: JumpComponent } | |
} | |
const jumpProto = { _name: 'jump' } | |
const jumpComponent = (power: number = 3): JumpComponent => { | |
return { | |
power | |
} | |
} | |
interface CanJump { | |
jump: typeof jump | |
} | |
function jump(this: Entity<WithName & WithJump>) { | |
console.log( | |
this.components.name + ' jumped! This high: ' + this.components.jump.power | |
) | |
} | |
type Rabbit = Entity<WithName & WithJump, CanJump> | |
const rabbit = (name: string): Rabbit => { | |
return { | |
id: id(), | |
components: { | |
name: nameComponent(name), | |
jump: jumpComponent() | |
}, | |
jump | |
} | |
} | |
const john = rabbit('john') | |
john.jump() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment