Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
node_modules
index.d.ts
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
ISC License

Copyright (c) 2022, Mapbox
Copyright (c) 2025, Mapbox

Permission to use, copy, modify, and/or distribute this software for any purpose
with or without fee is hereby granted, provided that the above copyright notice
Expand Down
37 changes: 0 additions & 37 deletions index.d.ts

This file was deleted.

31 changes: 27 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,27 @@

/**
* @typedef {Object} PotpackBox
* @property {number} w Box width.
* @property {number} h Box height.
* @property {number} [x] X coordinate in the resulting container.
* @property {number} [y] Y coordinate in the resulting container.
*/

/**
* @typedef {Object} PotpackStats
* @property {number} w Width of the resulting container.
* @property {number} h Height of the resulting container.
* @property {number} fill The space utilization value (0 to 1). Higher is better.
*/

/**
* Packs 2D rectangles into a near-square container.
*
* Mutates the {@link boxes} array: it's sorted (by height/width),
* and box objects are augmented with `x`, `y` coordinates.
*
* @param {PotpackBox[]} boxes
* @return {PotpackStats}
*/
export default function potpack(boxes) {

// calculate total box area and maximum box width
Expand All @@ -10,8 +33,8 @@ export default function potpack(boxes) {
maxWidth = Math.max(maxWidth, box.w);
}

// sort the boxes for insertion by height (or width if equal), descending
boxes.sort((a, b) => b.h - a.h || b.w - a.w);
// sort the boxes for insertion by height, descending
boxes.sort((a, b) => b.h - a.h);

// aim for a squarish resulting container,
// slightly adjusted for sub-100% space utilization
Expand Down Expand Up @@ -46,7 +69,7 @@ export default function potpack(boxes) {
if (box.w === space.w && box.h === space.h) {
// space matches the box exactly; remove it
const last = spaces.pop();
if (i < spaces.length) spaces[i] = last;
if (last && i < spaces.length) spaces[i] = last;

} else if (box.h === space.h) {
// space matches the box height; update it accordingly
Expand Down
Loading
Loading