0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

交換なのに二重計上? TypeScriptで見積もりの差額を計算する

0
Posted at

pc-workshop-budget-cover.png
PC構成の見積もりで、32,000円のGPUを48,000円のGPUに交換するとします。現在の残額が20,000円なら、必要なのは新しいGPUの全額ではなく、すでに合計に入っている旧GPUとの差額16,000円です。交換後は4,000円残ります。

候補の追加・交換・取り外しを一つの式にする

現在の残額に旧価格を戻し、新価格を引きます。未選択または取り外しに対応する側は0円です。以下は整数円を前提にした説明用の例です。

function previewRemaining(
  remainingYen: number,
  oldPriceYen: number | null,
  nextPriceYen: number | null,
): number {
  return remainingYen + (oldPriceYen ?? 0) - (nextPriceYen ?? 0);
}

console.assert(previewRemaining(20_000, 32_000, 48_000) === 4_000);
console.assert(previewRemaining(20_000, null, 20_000) === 0);
console.assert(previewRemaining(20_000, null, 22_000) === -2_000);
console.assert(previewRemaining(20_000, 32_000, null) === 52_000);

プレビューは選択確定前の表示に使い、確定時には保存済みの選択を差し替えます。ここで重要なのは、引数の remainingYen が旧パーツを含む確定済み構成から計算した残額であること。直前にプレビューした残額を次の候補に流用すると、差額を重ねて引いてしまいます。

価格は説明用の架空例です。題材の『猫のPC工房』

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?