Skip to content

Instantly share code, notes, and snippets.

@whitelizard
Last active June 17, 2020 18:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whitelizard/e127fa4c3b1da7d27107965b834e302b to your computer and use it in GitHub Desktop.
Save whitelizard/e127fa4c3b1da7d27107965b834e302b to your computer and use it in GitHub Desktop.
Functional style programming in JavaScript
// Circle data object creator
const circle = (pos = [0, 0], r = 0) => ({ pos, r, hits: 0 });
// Immutable-updates helpers
const incHits = obj => ({ ...obj, hits: (obj.hits || 0) + 1 });
const setPos = (obj, pos = [0, 0]) => ({ ...obj, pos });
// Circle computations
const area = r => r ** 2 * Math.PI;
const circlesIntersect = ({ r: r1, pos: [x1, y1] }, { r: r2, pos: [x2, y2] }) =>
Math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2) - r1 - r2 < 0;
const intersect = (c1, c2) => {
const hit = circlesIntersect(c1, c2);
return hit ? [hit, incHits(c1), incHits(c2)] : [hit, c1, c2];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment