ChemPal Documentation - v1.18.0
    Preparing search index...

    Function detectPriceDrops

    • Compares fresh prices with an alert's last known ones.

      Parameters

      Returns PriceComparison

      The drops and the new baseline

      A price seen for the first time, or no longer comparable, becomes the new baseline without a drop. A drop below the threshold leaves the baseline alone, so small drops add up. Prices that are missing this time keep their baseline.

      detectPriceDrops(alert, collectNativePrices(product), 5).drops;
      // [{ title: 'Acetone 500 g', from: 24, to: 19.5, currencyCode: 'USD' }]
      export function detectPriceDrops(
      alert: Pick<PriceAlert, 'id' | 'lastPrices'>,
      current: Record<string, PriceSnapshot>,
      minDropPercent: number,
      ): PriceComparison {
      const lastPrices = { ...alert.lastPrices };
      const drops: PriceDrop[] = [];
      let changed = false;

      for (const [id, fresh] of Object.entries(current)) {
      const previous = alert.lastPrices[id];
      if (!previous || !isComparable(previous, fresh, id === alert.id)) {
      lastPrices[id] = fresh;
      changed = true;
      continue;
      }

      const { price: from, currencyCode } = previous;
      const { price: to, title } = fresh;
      if (from !== to) changed = true;

      if (to < from) {
      if (dropPercent({ from, to }) < minDropPercent) continue;
      drops.push({ title, from, to, currencyCode });
      }
      lastPrices[id] = fresh;
      }

      drops.sort((a, b) => a.to / a.from - b.to / b.from);
      return { drops, changed, lastPrices };
      }