Created
August 8, 2023 12:28
-
-
Save lifeart/fd51d2653caf31432993d5bbe4561e6d to your computer and use it in GitHub Desktop.
Squares calculator
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
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