Looking to develop a function that can determine the best fitting image based on its size relative to its container.
- The image should not exceed the dimensions of the container either in width or height.
- The selected image should have minimal empty space around it
min(space)
.
I experimented with a simple JavaScript solution but I'm unsure if it's both efficient and elegant.
let arr = [{'id': 1, 'width': 10, 'height': 10},
{'id': 2, 'width': 20, 'height': 20},
{'id': 3, 'width': 30, 'height': 30},
{'id': 4, 'width': 40, 'height': 40},
{'id': 5, 'width': 50, 'height': 50}]
let height = 25
let width = 25
let best_min_height_delta = Infinity
let best_min_width_delta = Infinity
let best_empty_space = Infinity
let selected_id = -1
arr.forEach(element => {
if (height >= element.height && width >= element.width) {
let delta_height = height - element.height
let delta_width = width - element.width
if (delta_height < best_min_height_delta && delta_width < best_min_width_delta) {
let empty_space = delta_width + delta_width
if (empty_space < best_empty_space) {
best_min_width_delta = delta_width
best_min_height_delta = delta_height
best_empty_space = empty_space
selected_id = element.id
}
}
}
})
console.log('the winner is: ' + selected_id)