JSFiddle - React, Tailwind, and code Playground
by vjeux
JavaScript
function update_elements(widths, total_width, min_width) {
var elements = widths
.map(function (width, i) {
return {
width: Math.max(width, min_width),
pos: i
};
})
.sort(function (a, b) {
return a.width - b.width;
});
var pixels = elements
.reduce(function (acc, elem) {
return acc + elem.width;
}, 0) - total_width;
for (var i = 0; i < elements.length; ++i) {
var to_remove = Math.min(
Math.ceil(pixels / (elements.length - i)),
elements[i].width - min_width
);
elements[i].width -= to_remove;
pixels -= to_remove;
}
return elements
.sort(function (a, b) { return a.pos - b.pos; })
.map(function (elem) { return elem.width });
}
console.log(
update_elements([100, 200, 151, 171], 620, 120)
);