1.0.0 • Published 4 months ago

fitdim v1.0.0

Weekly downloads
-
License
Apache-2.0
Repository
github
Last release
4 months ago

fitdim

fitDim scales an N-dimensional array to perfectly fit within a bounding box, maintaining proportions. It supports both upscaling and downscaling to ensure the best possible fit.

Details

  • Works with any number of dimensions 2D, 3D, 4D, and beyond.
  • Fits perfectly inside a given bounding box.
  • Maintains proportions without distortion.
  • Supports both upscaling and downscaling.
  • Pure & atomic function, ideal for composable utility pipelines.

Install

npm install fitdim

Usage

import { fitDim } from 'fitdim';

const dims = [1920, 1080];
const maxDims = [1280, 800];

// ✅ Scales down to fit perfectly inside [1280, 800]
console.log(fitDim(dims, maxDims));
// [1280, 720]

// ✅ Scales up to fit inside [600, 800, 1000]
console.log(fitDim([300, 400, 500], [600, 800, 1000]));
// [600, 800, 1000]

// ✅ Slight upscaling to fit inside [400, 500, 600]
console.log(fitDim([300, 400, 500], [400, 500, 600]));
// [400, 500, 600]

// ✅ No change (already fits)
console.log(fitDim([300, 400, 500], [300, 400, 500]));
// [300, 400, 500]

API

fitDim(dims: number[], maxDims: number[]): number[]

Scales an N-dimensional array so that it fits perfectly within the given bounding box (maxDims), while maintaining proportions.

  • dims – The original array of dimensions (e.g., [width, height, depth]).
  • maxDims – The bounding box (maximum allowed dimensions).
  • Returns: A new array with adjusted dimensions.

⚠️ Errors

  • Throws an error if dims.length and maxDims.length do not match.

Cheatsheet Patterns

These patterns help apply common transformations using fitDim!

import fitDim from 'fitdim';

// 🔢 Round the result (Ceil, Floor, Nearest)
const dims = fitDim([1920, 1080], [1280, 800]);
const roundedDims = dims.map(Math.round);
// or use Math.floor / Math.ceil

// 🔍 Check if a resize occurred
const original = [1920, 1080];
const maxDims = [1280, 800];
const fitted = fitDim(original, maxDims);

const wasResized = !original.every((dim, i) => dim === fitted[i]);
console.log(wasResized); // true

Example Use Cases

  • Image Processing – Prevent excessive pixel count while keeping aspect ratio.
  • 3D Modeling – Ensure objects stay within a total volume constraint.
  • Physics Simulations – Rescale multi-dimensional datasets.
  • Grid/Matrix Operations – Adjust data structures without exceeding capacity.

Related Packages

These link might be suffixed with "-node" in the future if conflicts arise.

Links

Development Homepage

https://github.com/alexstevovich/fitdim

This link might be suffixed with "-node" in the future if conflicts arise.

License

Licensed under the Apache License 2.0.