UNPKG

fitdim

Version:

Scales an N-dimensional array to perfectly fit within a bounding box, maintaining proportions.

66 lines (61 loc) 2.28 kB
/* ******************************************************* * fitdim * * @license * * Apache-2.0 * * Copyright 2015-2025 Alex Stevovich * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @meta * * package_name: fitdim * file_name: src/index.js * purpose: Core functionality and exports combined. * * @system * * generated_on: 2025-03-15T03:33:43.115Z * certified_version: 1.0.0 * file_uuid: 6ce858a0-923d-4bd0-83a5-606373f111ee * file_size: 2278 bytes * file_hash: b41932bdc85c5b59b347cf0f367cf19da6a8e22249917d4d6e7aa4c57fe2654d * mast_hash: 834cb5c884b0a2b3de013943ff649e57ee978e2e1c215aba849f1502a1bc980a * generated_by: preamble on npm! * * [Preamble Metadata] ********************************************************/ /** * Scales an N-dimensional array to perfectly fit within a bounding box, * maintaining proportions. This function supports both **upscaling** and **downscaling**. * * @param {number[]} dims - Array of dimensions (e.g., `[width, height, depth]`). * @param {number[]} maxDims - Array of maximum allowed dimensions. * @returns {number[]} - The new dimensions, scaled proportionally to fit perfectly. */ export function fitDim(dims, maxDims) { if (dims.length !== maxDims.length) { throw new Error( `Mismatched dimensions: got ${dims.length} dims but expected ${maxDims.length}`, ); } // Compute the scaling factor for each axis const scaleFactors = maxDims.map((max, i) => max / dims[i]); // Choose the **smallest** scale factor to ensure all dimensions fit inside the bounding box const scaleFactor = Math.min(...scaleFactors); // Apply uniform scaling to maintain proportions return dims.map((dim) => dim * scaleFactor); } export default fitDim;