Skip to content

Instantly share code, notes, and snippets.

@franga2000
Created December 16, 2017 14:45
Show Gist options
  • Save franga2000/3300cc253c13e72887f770fd8649a073 to your computer and use it in GitHub Desktop.
Save franga2000/3300cc253c13e72887f770fd8649a073 to your computer and use it in GitHub Desktop.
/*
* Sort a list of django-taggit-labels tags so they use as few rows as possible.
* Using the first-fit algorithm (https://en.wikipedia.org/wiki/Bin_packing_problem#First-fit_algorithm)
*/
function packTags(tags) {
var $tags = $(tags);
var max = $tags.outerWidth(true);
function widths(els) {
var w = 0;
$(els).each((i,el) => {
w += $(el).outerWidth(true);
});
return w;
}
var bins = [];
// TODO: Put the tags in a separate array so it can be sorted before packing
$tags.find(".taggit-tag").each((i, tag) => {
var width = widths(tag);
for (let bin of bins) {
if (max - widths(bin) >= width) {
bin.push(tag);
tag = null;
break;
}
}
if (tag != null) {
bins.push([tag]);
}
});
for (tag of [].concat(...bins)) {
$tags.append(tag)
}
}
// Actually running it
packTags("#id_oznake");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment