Skip to content

Instantly share code, notes, and snippets.

@lifeart
Created August 8, 2023 12:28
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 lifeart/fd51d2653caf31432993d5bbe4561e6d to your computer and use it in GitHub Desktop.
Save lifeart/fd51d2653caf31432993d5bbe4561e6d to your computer and use it in GitHub Desktop.
Squares calculator
type Square = {
x: number;
width: number;
}
const squares: Square[] = [
{
x: 0,
width: 10,
},
{
x: 10,
width: 10,
},
{
x: 7,
width: 10,
}, {
x: 21,
width: 10,
}
];
const sortedSquares = squares.sort((a, b) => a.x - b.x);
function hasOverlap(a, b) {
return a.x <= b.x + b.width && b.x <= a.x + a.width;
}
const standaloneSquares = sortedSquares.reduce((acc, square) => {
if (acc.current === null) {
acc.current = square;
return acc;
} else if (hasOverlap(acc.current, square)) {
acc.current = {
x: Math.min(acc.current.x, square.x),
width: Math.max(acc.current.x + acc.current.width, square.x + square.width) - Math.min(acc.current.x, square.x),
};
} else {
acc.prev.push(acc.current);
acc.current = square;
}
return acc;
}, {
prev: [],
get all() {
return [...this.prev, this.current];
},
current: null,
} as {
prev: Square[];
all: Square[];
current: Square | null;
})
console.log(standaloneSquares.all);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment