Created
January 3, 2022 14:29
-
-
Save SalatielSauer/dc0aa7eecec0d092f81a2f4fb2dc9ac5 to your computer and use it in GitHub Desktop.
JavaScript function to get the most rectangular image dimension that fits a certain number of pixels with the least (or no) addition of extra pixels.
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 pixelsIntoRect(n, k){ | |
var max = ~~Math.sqrt(n); | |
return Array.from({length: max}, (_, i, a) => [n%(max-i), max-i]) | |
.sort((a, b) => a[0] - b[0]) | |
.slice(0, k) | |
.map(t => [Math.ceil(n/t[1]), t[1], (Math.ceil(n/t[1])*t[1])-n]) | |
.filter(a => Math.round(a[1]/a[0]) == 1) | |
.sort((a, b) => a[2] - b[2]) | |
} | |
pixelsIntoRect(262144) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment