Created
April 24, 2019 06:47
-
-
Save rgruesbeck/4b26933d8f4afeb997770361720f8daf to your computer and use it in GitHub Desktop.
functional sprite: composed move function
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
const withConstructor = constructor => o => ({ | |
__proto__: { constructor }, | |
...o | |
}); | |
const mix = (...fns) => x => fns.reduce((y, f) => f(y), x); | |
const canMove = o => { | |
return { | |
...o, | |
move (x, y, m) { | |
let modifier = this.speed ? this.speed * m : m; | |
let dx = x === 0 ? this.x : this.x + (x * modifier); | |
let dy = y === 0 ? this.y : this.y + (y * modifier); | |
console.log('moving', dx, dy); | |
this.x = dx; | |
this.y = dy; | |
} | |
}; | |
}; | |
const image = ({ ctx, image, x = 0, y = 0, w = 50, h = 50 }) => o => { | |
return { | |
...o, | |
ctx, | |
image, | |
x, | |
y, | |
w, | |
h | |
}; | |
}; | |
const createSprite = (base) => mix( | |
image(base), | |
canMove, | |
withConstructor(createSprite) | |
)({}); | |
const mySprite = createSprite({ ctx: 'ctx', image: 'image' }); | |
console.log(mySprite); | |
mySprite.move(1, 1, 1); | |
console.log(mySprite); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment