Calculate fraction as value relative to other fractions

淺唱寂寞╮ 提交于 2020-03-04 08:27:54

问题


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: 200px

And items: [0.5, 1, 50px]

I should be able to calculate the fractional ones relative to each other:

item1: 50 (half the size of item 2)
item2: 100 (double the size of item 1)
item3: 50 (static size not a fraction)

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 derivedItems = items.map(item => {
  if (item > 1) {
    // A static value.
    return item;
  }
  
  // How to calculate this fractional item relative to others?
  return item;
});

console.log(derivedItems);

回答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));



回答2:


let compute = (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);


来源:https://stackoverflow.com/questions/58737641/calculate-fraction-as-value-relative-to-other-fractions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!