react-columns
Version:
React component for rendering columns from a list of children with horizontal ordering
47 lines (41 loc) • 1.39 kB
JavaScript
export default function mapNodesToColumns() {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
_ref$children = _ref.children,
children = _ref$children === undefined ? [] : _ref$children,
_ref$columns = _ref.columns,
columns = _ref$columns === undefined ? 1 : _ref$columns,
_ref$dimensions = _ref.dimensions,
dimensions = _ref$dimensions === undefined ? [] : _ref$dimensions;
var nodes = [];
var heights = [];
if (columns === 1) {
return children;
}
// use dimensions to calculate the best column for each child
if (dimensions.length && dimensions.length === children.length) {
for (var i = 0; i < columns; i++) {
nodes[i] = [];
heights[i] = 0;
}
children.forEach(function (child, i) {
var _dimensions$i = dimensions[i],
width = _dimensions$i.width,
height = _dimensions$i.height;
var index = heights.indexOf(Math.min.apply(Math, heights));
nodes[index].push(child);
heights[index] += height / width;
});
}
// equally spread the children across the columns
else {
var _loop = function _loop(_i) {
nodes[_i] = children.filter(function (child, j) {
return j % columns === _i;
});
};
for (var _i = 0; _i < columns; _i++) {
_loop(_i);
}
}
return nodes;
}