Skip to content

applyHysteresis function ​

Updates an on/off state with hysteresis: on at or above highThreshold, off at or below lowThreshold, unchanged in between. A noisy value near a threshold no longer makes the state flicker.

ts
import { applyHysteresis } from 'utils';

Signature ​

ts
export function applyHysteresis(value: number, isOn: boolean, lowThreshold: number, highThreshold: number): boolean

Parameters ​

NameDescription
valueThe latest value.
isOnThe current state.
lowThresholdThe value at or below which the state switches off.
highThresholdThe value at or above which the state switches on.

Returns ​

The new state.

Example ​

ts
isAlarmOn = applyHysteresis(temperature, isAlarmOn, 85, 90); // on at 90 °C, off under 85 °C

Tests ​

Line coverage: 100 %.

  • ✅ turns 95 with state false into true
  • ✅ turns 90 with state false into true
  • ✅ turns 87 with state false into false
  • ✅ turns 87 with state true into true
  • ✅ turns 85 with state true into false
  • ✅ turns 80 with state true into false
  • ✅ does not flicker around the high threshold

Source ​

src/math/apply-hysteresis.ts (on GitHub)

Source code
ts
/**
 * Updates an on/off state with hysteresis: on at or above `highThreshold`, off at or below `lowThreshold`,
 * unchanged in between. A noisy value near a threshold no longer makes the state flicker.
 *
 * @param value - The latest value.
 * @param isOn - The current state.
 * @param lowThreshold - The value at or below which the state switches off.
 * @param highThreshold - The value at or above which the state switches on.
 * @returns The new state.
 * @example
 * isAlarmOn = applyHysteresis(temperature, isAlarmOn, 85, 90); // on at 90 °C, off under 85 °C
 */
export function applyHysteresis(value: number, isOn: boolean, lowThreshold: number, highThreshold: number): boolean {
  return value >= highThreshold || (value > lowThreshold && isOn);
}
Test file
ts
import { applyHysteresis } from './apply-hysteresis';

describe(applyHysteresis, () => {
  it.for([
    [95, false, true],
    [90, false, true],
    [87, false, false],
    [87, true, true],
    [85, true, false],
    [80, true, false],
  ] as const)('turns %s with state %s into %s', ([value, isOn, expected]) => {
    expect(applyHysteresis(value, isOn, 85, 90)).toBe(expected);
  });

  it('does not flicker around the high threshold', () => {
    let isOn = false;
    const states = [89, 91, 89, 88, 91, 86, 84].map((value) => {
      isOn = applyHysteresis(value, isOn, 85, 90);
      return isOn;
    });
    expect(states).toStrictEqual([false, true, true, true, true, true, false]);
  });
});

Keywords: apply, hysteresis, math, function

Generated from the JSDoc of the sources.