Testing filter vs if

Benchmark created on


Setup

const a = {
  uid: '1',
  duplicateCount: 1,
  selected: {},
  positions: {},
  action: {
    type: 'addSelected',
    keys: [],
    positions: {
      '1-1-1-boards': {
        bottom: 1,
        left: 1,
        right: 1,
        top: 1,
        element: 'element',
      },
    },
  },
};
const b = {
  uid: '2',
  duplicateCount: 4,
  selected: {},
  positions: {},
  action: {
    type: 'addSelected',
    keys: [],
    positions: {
      '1-1-1-boards': {
        bottom: 1,
        left: 2,
        right: 1,
        top: 1,
        element: 'element 2',
      },
    },
  },
};

Test runner

Ready to run.

Testing in
TestOps/sec
Using filter
const compareHistory = (a, b) => {
  const isEqual = (val1, val2) => {
    if (typeof val1 === 'object' && val1 !== null && typeof val2 === 'object' && val2 !== null) {
      const problematicFields = ['uid', 'duplicateCount', 'element', 'system', 'imageBlob'];
      const keys1 = Object.keys(val1).filter((key) => problematicFields.includes(key));
      const keys2 = Object.keys(val2).filter((key) => problematicFields.includes(key));

      if (keys1.length !== keys2.length) {
        return false;
      }

      for (const key of keys1) {
        if (!isEqual(val1[key], val2[key])) {
          return false;
        }
      }

      return true;
    }
    return val1 === val2;
  };

  return isEqual(a, b);
};

compareHistory(a, b)
ready
Using if
const compareHistory = (a, b) => {
  const isEqual = (val1, val2) => {
    if (typeof val1 === 'object' && val1 !== null && typeof val2 === 'object' && val2 !== null) {
      const keys1 = Object.keys(val1);
      const keys2 = Object.keys(val2);

      if (keys1.length !== keys2.length) {
        return false;
      }

      for (const key of keys1) {
        // problematic fields
        if (
          key !== 'uid' &&
          key !== 'duplicateCount' &&
          key !== 'element' &&
          key !== 'system' &&
          key !== 'imageBlob'
        ) {
          if (!isEqual(val1[key], val2[key])) {
            return false;
          }
        }
      }

      return true;
    }
    return val1 === val2;
  };

  return isEqual(a, b);
};

compareHistory(a, b)
ready

Revisions

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