Search code examples
javascriptcomparison

Javascript Check if three values are equal within tolerance of 2


I want to check if 3 RGB values are basically equal but sometimes the values are 1 or even 2 out either way so it's not so straightforward. So 90,90,90 should be equal as should 90,88,90.

At the minute the best I came up with was something like:

if (r != g && r != b) {
  if ((r != b && r != (b - 1))) {
    // etc
  }
}


Expected output:
91,90,90 = true
93,89,93 = false
91,90,89 = true

Solution

  • You can use every() on the array and check if the absolute difference b/w the each value with minimum(or maximum) is less than 2 or equal to 2

    const checkRBG = arr => {
      let min = Math.min(...arr);
      return arr.every(x => Math.abs(min-x) <=2);
    }
    
    const tests = [
      [91,90,90],
      [93,89,93],
      [91,90,89],
      [90,88,92]
    ]
    
    tests.forEach(x => console.log(checkRBG(x)))