Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading