Skip to content

Instantly share code, notes, and snippets.

@whitelizard
Last active June 17, 2020 12:24
Show Gist options
  • Save whitelizard/ff00c9770204f4e28d0f50f369e7be7b to your computer and use it in GitHub Desktop.
Save whitelizard/ff00c9770204f4e28d0f50f369e7be7b to your computer and use it in GitHub Desktop.
Factory pattern in JavaScript
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