Find matching threshold

Benchmark created on


Setup

  const defaultMin = 0;
    const thresholdsData = [
      { value: 55, color: 'red', name: 'bad' },
      { value: 20, color: 'yellow', name: 'warning' },
      { value: 10, color: 'light-green', name: 'good' },
      { value: 5, color: 'green', name: 'very very good' },
    ];

    const testcases = [
      { value: 56, expected: thresholdsData[0], message: 'the first' },
      { value: 22, expected: thresholdsData[1], message: 'the second' },
      { value: 19, expected: thresholdsData[2], message: 'the third' },
      { value: 5, expected: thresholdsData[3], message: 'the fourth' },
      { value: 1, expected: undefined, message: 'none of the' },
    ];

Test runner

Ready to run.

Testing in
TestOps/sec
Current
const current = (
  value,
  thresholdData,
  min
) =>
  [...thresholdData]
    .sort((a, b) => b.value - a.value)
    .find((threshold) => value + min >= threshold.value);
    
testcases.forEach(c => current(c.value, thresholdsData, defaultMin))    
ready
Proposed
const proposed = (
  value,
  thresholdData,
  min,
) => {
  const filteredThresholdData = thresholdData.filter(
    (threshold) => value + min >= threshold.value,
  );

  if (!filteredThresholdData.length) {
    return undefined;
  }

  return filteredThresholdData.reduce(
    (final, current) => (current.value > final.value ? current : final),
    filteredThresholdData[0],
  );
};

testcases.forEach(c => proposed(c.value, thresholdsData, defaultMin)) 
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.