Skip to content

Instantly share code, notes, and snippets.

@Oikio
Created November 22, 2017 13:26
Show Gist options
  • Save Oikio/16c33fdfc6f0d99a212fd10fe84b5143 to your computer and use it in GitHub Desktop.
Save Oikio/16c33fdfc6f0d99a212fd10fe84b5143 to your computer and use it in GitHub Desktop.
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