Last active
June 17, 2020 12:24
-
-
Save whitelizard/ff00c9770204f4e28d0f50f369e7be7b to your computer and use it in GitHub Desktop.
Factory pattern in JavaScript
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
function makeCircle(pos = [0, 0], r = 0) { | |
let hits = 0; | |
const obj = { | |
pos, | |
getR: () => r, | |
getHits: () => hits, | |
incHits: () => (hits += 1), | |
area: () => r ** 2 * Math.PI, | |
intersect: (circle) => { | |
const h = Math.sqrt( | |
(obj.pos[0] - circle.pos[0]) ** 2 + (obj.pos[1] - circle.pos[1]) ** 2, | |
); | |
const hit = h - r - circle.getR() < 0; | |
if (hit) { | |
obj.incHits(); | |
circle.incHits(); | |
} | |
return hit; | |
}, | |
}; | |
return obj; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment