计算分数作为相对于其他分数的值 [英] Calculate fraction as value relative to other fractions

查看:96
本文介绍了计算分数作为相对于其他分数的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法显示代码的道歉,只是不确定该如何处理.

Apologies that I can't show code I'm just not sure how to go about this.

我想实现类似于display: flex/grid的分数:

I would like to achieve something like display: flex/grid does with fractions:

给出容器宽度:200px

和项目:[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);

推荐答案

减去静态项目后,计算分数项目的总和,然后可以计算每个值相对于剩余容器宽度的百分比(减去静态项目)总和):

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

这篇关于计算分数作为相对于其他分数的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆