reactjs 如何在React js中用两个常量数组相乘

bf1o4zei  于 2023-01-25  发布在  React
关注(0)|答案(1)|浏览(175)

我是react js的新手,尝试使用两个不同的常量数组进行乘法运算

export const transactions = [
  {
    sequence_number: 3,
    book_date: "2020-01-02",
    account_id: 1,
    value: 150123,
  },
  {
    sequence_number: 3,
    book_date: "2020-03-02",
    account_id: 2,
    value: 192842,
  },
  {
    sequence_number: 2,
    book_date: "2020-04-03",
    account_id: 2,
    value: 142592,
  },
];

export const monthly_rates = [
  {
    effective_date: "2020-01-01",
    multiplier: 0.9,
  },
  {
    effective_date: "2020-02-01",
    multiplier: 1.3,
  },
  {
    effective_date: "2020-03-03",
    multiplier: 1.5,
  },
  {
    effective_date: "2020-04-01",
    multiplier: 1.3,
  },
  {
    effective_date: "2020-05-15",
    multiplier: 1.5,
  },
];

我想用乘法计算总值,假设

{
    sequence_number: 2,
    book_date: "2020-04-03",
    account_id: 2,
    value: 142592,
  },

我们可以看到,2020年4月3日生效的比率为1.3值=乘数 * 值= 1.3 * 142592

mftmpeh8

mftmpeh81#

如果我没猜错的话,你想通过比较effective_date和book_date得到乘数,然后你想计算该汇率乘数的交易次数乘数的值。
例如,如果book_date为:2020-04-01

  • 如果存在有效日期早于2020-04-1的汇率,则该汇率就是我们要查找的汇率。如果存在多个有效日期,则需要最新的汇率。

如果我说错了请纠正我。
我创建并测试了这个函数,它似乎工作:

const multiplyByTransaction = (transaction) => {
  let multiplier = null;

  // sort in ascending order in case they are not sorted.
  // you can remove the sort() if you have them sorted already
  const sorted_rates = monthly_rates.sort(
    (a, b) => a.effective_date - b.effective_date
  );

  for (let index = 0; index < sorted_rates.length; index++) {
    if (
      Date.parse(transaction.book_date) <
      Date.parse(sorted_rates[index].effective_date)
    ) {
      multiplier = sorted_rates[index > 0 ? --index : index].multiplier;
      break;
    }
  }

  // this means that there isn't any effective_date that is greater than book_date of the transaction
  // so we assign the latest rate's multiplier to our multiplier
  if (!multiplier) {
    multiplier = sorted_rates[sorted_rates.length - 1].multiplier;
  }

console.log(
    `Calculating: Multiplier => ${multiplier} * value => ${
      transaction.value
    } = ${multiplier * transaction.value}`
  );
  return multiplier * transaction.value;
};

multiplyByTransaction(transactions[1]) // will log: Calculating: Multiplier => 1.3 * value => 192842 = 250694.6

希望能有所帮助!

相关问题