weekdayBaseline.test.ts 2.04 KB
import { describe, expect, it } from 'vitest';
import { weekdayBaseline } from './weekdayBaseline';

/**
 * 「按星期」的平均线。
 *
 * 这条线以前是 matched / 7。它只在统计期恰好是整周时才对 —— 一旦窗口是近 10 天、
 * 或者数据只覆盖 26 天,七个星期几出现的次数就不一样,等量摊平均线会让出现次数少的
 * 那几天全部「高于平均」,读出来是一个并不存在的周末高峰。
 */
describe('weekdayBaseline · 按天数折算的期望', () => {
  it('整周窗口:七天平分,与旧口径一致', () => {
    const b = weekdayBaseline(700, [3, 3, 3, 3, 3, 3, 3]);
    for (const v of b) expect(v).toBeCloseTo(100, 10);
  });

  it('非整周窗口:按各星期几出现的天数摊,不是七等分', () => {
    // 10 天:周一 / 周二各出现 2 次,其余各 1 次(第 10 天回到周一)
    const days = [1, 1, 1, 1, 1, 1, 1]; // 周日..周六,基础各 1 天
    days[1] += 1; // 周一 2 天
    days[2] += 1; // 周二 2 天
    days[5] += 1; // 周五 2 天
    expect(days.reduce((a, b) => a + b, 0)).toBe(10);

    const b = weekdayBaseline(1000, days);
    // 出现 2 天的档期望 200,出现 1 天的档期望 100 —— 旧口径是 142.86,两头都错
    expect(b[1]).toBeCloseTo(200, 10);
    expect(b[0]).toBeCloseTo(100, 10);
    expect(b[1]).not.toBeCloseTo(1000 / 7, 3);
  });

  it('期望之和恒等于命中数:高于与低于能互相抵消', () => {
    const days = [4, 5, 4, 4, 5, 4, 4];
    const sum = weekdayBaseline(1234, days).reduce((a, b) => a + b, 0);
    expect(sum).toBeCloseTo(1234, 8);
  });

  it('窗口为空时全 0,不返回 NaN', () => {
    const b = weekdayBaseline(0, [0, 0, 0, 0, 0, 0, 0]);
    expect(b).toEqual([0, 0, 0, 0, 0, 0, 0]);
    // 缺项(老数据没有 weekdayDays)按 0 天处理,同样不能出现 NaN
    const partial = weekdayBaseline(10, [3, 3, 3]);
    expect(partial.every((v) => Number.isFinite(v))).toBe(true);
    expect(partial.reduce((a, b2) => a + b2, 0)).toBeCloseTo(10, 10);
  });
});