Skip to content Skip to sidebar Skip to footer

Calculate Fraction As Value Relative To Other Fractions

Apologies that I can't show code I'm just not sure how to go about this. I would like to achieve something like display: flex/grid does with fractions: Given a container width: 200

Solution 1:

After subtracting the static items, calculate the sum of fractional items, then you can calculate the percentage of each value relative to the remaining container width (minus the static item sum):

const totalSize = 900;
const items = [1, 0.2, 75, 0.6, 1, 100];
const totalStaticSize = items.filter(n => n > 1).reduce((acc, n) => acc + n, 0);
const sum = derivedItems.reduce((a, b) => a + b, 0);
const percentages = derivedItems.map(d => d / sum);
const relativeToContainer = percentages.map(p => p * (totalSize - totalStaticSize));

Solution 2:

letcompute = (values, total) => {
  let parts = values.map(value => ({value: parseFloat(value), absolute: value.endsWith('px')}));
  let totalAbsolutes = parts.filter(p => p.absolute).reduce((sum, p) => sum + p.value, 0);
  let totalFractions = parts.filter(p => !p.absolute).reduce((sum, p) => sum + p.value, 0);
  return parts.map(p => (p.absolute ? p.value : p.value / totalFractions * (total - totalAbsolutes)) + 'px');
};

let computedValues = compute(['0.5', '1', '50px'], 200);
console.log(computedValues);

Post a Comment for "Calculate Fraction As Value Relative To Other Fractions"