Skip to content

hasSignificantChange function ​

Checks whether a value moved enough since the displayed one to be worth a render (a deadband). A switch between a number and NaN always counts.

ts
import { hasSignificantChange } from 'utils';

Signature ​

ts
export function hasSignificantChange(previous: number, next: number, threshold = 0): boolean

Parameters ​

NameDescription
previousThe displayed value.
nextThe new value.
thresholdThe smallest change worth a render. Defaults to 0.

Returns ​

true when |next - previous| >= threshold.

Example ​

ts
hasSignificantChange(10, 10.5, 0.1); // true
hasSignificantChange(10, 10.05, 0.1); // false

Tests ​

Line coverage: 100 %.

  • ✅ compares 10 → 10.05 with threshold 0.1: false
  • ✅ compares 10 → 10.5 with threshold 0.1: true
  • ✅ compares 1000 → 1000.1 with threshold 0.1: true
  • ✅ compares 10 → 10.099 with threshold 0.1: false
  • ✅ compares 10 → 9.8 with threshold 0.1: true
  • ✅ compares 10 → 10 with threshold 0: true
  • ✅ compares NaN → 10 with threshold 0.1: true
  • ✅ compares 10 → NaN with threshold 0.1: true
  • ✅ compares NaN → NaN with threshold 0.1: false
  • ✅ takes the defaults

Source ​

src/math/has-significant-change.ts (on GitHub)

Source code
ts
/**
 * Checks whether a value moved enough since the displayed one to be worth a render (a deadband). A switch
 * between a number and `NaN` always counts.
 *
 * @param previous - The displayed value.
 * @param next - The new value.
 * @param threshold - The smallest change worth a render. Defaults to `0`.
 * @returns `true` when `|next - previous| >= threshold`.
 * @example
 * hasSignificantChange(10, 10.5, 0.1); // true
 * hasSignificantChange(10, 10.05, 0.1); // false
 */
export function hasSignificantChange(previous: number, next: number, threshold = 0): boolean {
  return Math.abs(next - previous) >= threshold || Number.isNaN(previous) !== Number.isNaN(next);
}
Test file
ts
import { hasSignificantChange } from './has-significant-change';

describe(hasSignificantChange, () => {
  it.for([
    [10, 10.05, 0.1, false],
    [10, 10.5, 0.1, true],
    [1000, 1000.1, 0.1, true],
    [10, 10.099, 0.1, false],
    [10, 9.8, 0.1, true],
    [10, 10, 0, true],
    [NaN, 10, 0.1, true],
    [10, NaN, 0.1, true],
    [NaN, NaN, 0.1, false],
  ] as const)('compares %s → %s with threshold %s: %s', ([previous, next, threshold, expected]) => {
    expect(hasSignificantChange(previous, next, threshold)).toBe(expected);
  });

  it('takes the defaults', () => {
    expect(hasSignificantChange(1, 1.000_001)).toStrictEqual(hasSignificantChange(1, 1.000_001, 0));
  });
});

Keywords: has, significant, change, math, function

Generated from the JSDoc of the sources.