0

I want to implement an equality function in JavaScript using dynamic programming.

This is what i have come up with.

function isEqualFunction(args: any): boolean {
    // Here a1 and a2 are two objects to be compared(they cannot be lists)
    // a1a2CombinedKeys is an object that combines keys of a1 and a2,
    // comparisonArgs is an object that needs to be passed to each comparison function for 
    // nested objects in a1 and a2,
    // nestedArrayOrObjCompareFunc is an object which contains comparison function for each 
    // nested object in a1 or a2.
    const { a1, a2, a1a2CombinedKeys, comparisonArgs, nestedArrayOrObjCompareFunc, } = args;
    return Object.keys(a1a2CombinedKeys).every((objKey) => {
        const a1Value = a1[objKey], a2Value = a2[objKey];
        if (a1Value && a2Value) {
            if (Array.isArray(a1Value)) {
                const { isPropEqualFunction } = nestedArrayOrObjCompareFunc[objKey];
                const { a1a2NestedKeys, nestedObjComparFunc: listItemObjComparFunc } = isPropEqualFunction(comparisonArgs);
                return a1Value.every((a1ObjListItem) => a2Value.find((a2ObjListItem) => isEqualFunction({
                    a1: a1ObjListItem, a2: a2ObjListItem, comparisonArgs,
                    a1a2CombinedKeys: a1a2NestedKeys, nestedArrayOrObjCompareFunc: listItemObjComparFunc,
                })))
            } else if (typeof a1Value === 'object') {
                const { isPropEqualFunction } = nestedArrayOrObjCompareFunc[objKey];
                const { a1a2NestedKeys, nestedObjComparFunc: nestedObjComparFunc } = isPropEqualFunction(comparisonArgs);
                return isEqualFunction({
                    a1: a1Value, a2: a2Value, comparisonArgs,
                    a1a2CombinedKeys: a1a2NestedKeys, nestedArrayOrObjCompareFunc: nestedObjComparFunc,
                })
            } else {
                return a1Value === a2Value
            }
        } else if (!a1Value && !a2Value) {
            return true;
        } else {
            return false;
        }
    });
}

I cannot compare the hash of two objects as some of the nested elements have an id prop.

I am not sure if this is foolproof, but it seems good to me.

Also, I am struggling to create a typescript definition for the same. Any help on that front would also be highly appreciated.

LarrySnyder610
  • 2,277
  • 12
  • 24
Amol Gupta
  • 2,054
  • 1
  • 14
  • 29

0 Answers0