How to refactor this to provide the property name (string)?

Advertisements

The following is working code. The question is specifically about refactoring to provide the string for property name used to compare by isSame. Perhaps better renamed to isPropValueSame.

import * as _ from 'lodash';

const diff = _.differenceWith(sourceList, comparatorList, this.isSame);

isSame = (objA: any, objB: any) => (_.has(objA, 'id') && _.has(objB, 'id') ? objA['id'] === objB['id'] : false);

Looking to pass field/prop name string like this.isSame('id'));

objA and objB would be the items from lists: sourceList and comparatorList and lists might look like:

const sourceList = [
    { id: 1, prop2: { prop21: someValue }, prop3: prop3Value },
    { id: 2, prop2: { prop21: someValue }, prop3: prop3Value },
    { id: 3, prop2: { prop21: someValue }, prop3: prop3Value },
];
const comparatorList = [
    { id: 1, prop2: { prop21: someValue }, prop3: prop3Value },
    //{ id: 2, prop2: { prop21: someValue }, prop3: prop3Value },
    { id: 3, prop2: { prop21: someValue }, prop3: prop3Value },
];

With above test case data (note comparatorList has second item commented out), then the output of comparator would return the item where id equals 2 because it does not find it during comparison by delegate function isSame.

>Solution :

Not sure if you’re looking for more than just a closure around the key – doesn’t seem like type-safety is a concern for you so could be as simple as:

const isSame = (key: string) => (objA: unknown, objB: unknown) =>
  _.has(objA, key) && _.has(objB, key) && _.get(objA, key) === _.get(objB, key);

Sandbox

If you can live without having type checking on the key then that would suffice, but if you need it then I’d refer you to this previous answer on recursive access paths.

Leave a ReplyCancel reply