Giter Site home page Giter Site logo

tjmoses / crud-compare Goto Github PK

View Code? Open in Web Editor NEW
17.0 2.0 2.0 1.33 MB

Compare JavaScript Objects, Array of Objects, and/or Array of Primitives to get created, modified, and deleted values.

Home Page: https://npmjs.com/package/crud-object-diff

License: MIT License

JavaScript 64.24% TypeScript 35.76%
javascript objects crud compare-objects react-object-compare js-array-compare js-object-compare js-batch-compare js-object-diff hacktoberfest

crud-compare's Introduction

CRUD Compare - JS State Comparison Helper

npm npm bundle size Coverage GitHub Dependencies PRs Welcome CircleCI

This is a very ✌ lightweight and ⚡️ fast library for comparing objects, arrays, and arrays of objects to get the Created, Updated, & Deleted values (helpful for state comparisons).

Install

npm install crud-object-diff

Usage

Comparing Arrays of Objects

  • Method: compareObjectVals

  • Parameters: toCompareVals: [Object[], Object[]], key?: string|string[]

  • Returns: { createdVals: Object[]|null, updatedVals: Object[]|null, deletedVals: Object[]|null }

  • Provides: Created, Updated, and Deleted values (via separate arrays) from comparing two arrays of objects.

    • It is recommended to provide a related unique key (i.e. primary key on data) between the objects to be compared using the compareObjectVals function. A single or composite (several keys) key can be provided in an array for relatedObjectKey.
    • Without giving a related key, the algorithm traverses every single key in each provided object looking for when a single object key is matched along with a value with equivalence between the matching found key.
    • The values of the returned created, updated, or deleted arrays from compareObjectVals / compareArrayVals functions will be null if they do not exist.
const originalArrayOfObjects = [{ one: 1, two: 2 }, { test: undefined }];
const newArrayOfObjects = [{ one: 1, two: null }, { one: 22, five: 5 }]
const relatedObjectKey = 'one';

const { createdVals, updatedVals, deletedVals } = compareObjectVals(
  [originalArrayOfObjects, newArrayOfObjects],
  relatedObjectKey // Not required, but suggested for speed.
);

console.log(createdVals); // [{ one: 22, five: 5 }]
console.log(updatedVals); // [{ one: 1, two: null }]
console.log(deletedVals); // [{ test: undefined }]

See further examples here.

Comparing Arrays

  • Method: compareArrayVals

  • Parameters: toCompareVals: [any[], any[]]

  • Returns: { createdVals: any[] | null, deletedVals: any[] | null }

  • Provides: Created and Deleted values between two arrays of primitives (strings, numbers, etc.) using the compareArrayVals function.

const originalArrayItem = [1, 2, 'five', true, 33];
const updatedArrayItem = [1, 'seven', true, 33];

const { createdVals, deletedVals } = compareArrayVals(
  [ originalArrayItem, updatedArrayItem ]
);
console.log(createdVals); // ['seven']
console.log(deletedVals); // [2, 'five']

See further examples here.

Comparing Two Arrays or Two Objects for Equivalence via helper functions

isEqualObject(a: Object, b: Object): Boolean

isEqualArray(a: any[], b: any[]): Boolean

  • Deep Object and Array comparing helper functions are provided for quick equivalence checks using the isEqualObject or isEqualArray functions. *Note: Object.is() is used for primative data type comparison checks.
const obj1 = {a: 1, b: 2, c: {'one': 1, 'two': [{ 2: 1, 44:3 }]}};
const obj2 = {a: 1, b: 2, c: {'one': 1, 'two': [{ 2: 1, 44:3 }]}};
const areObjectsEquivalent = isEqualObject(obj1, obj2); // true
const array1 = [Symbol('33')];
const array2 = ['one', 'two'];
const areArraysEquivalent = isEqualArray(array1, array2); // false

See further examples here

To support, Please 🌟 if you used / like this library!

Todo

  • Add more tests for edge cases.
  • Update prettier and fix the linter.
  • Get the Google Closure Compiler working w/ the advanced compile setting, and fix types in the code to reach ~99%.

Contributing

Please see the contributing guidelines here for further information. All contributions are appreciated, even if they are just comments from issues.

License

MIT

crud-compare's People

Contributors

dependabot[bot] avatar tjmoses avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

crud-compare's Issues

feature request: return indexes

add functionality for return indexed

e.g. add option to return keys { extend: true }, and we can get the result

// from 
[{ one: 22, five: 5 }]

// to
[
  {
    value: { one: 22, five: 5 },
    index: 3
  }
]

this is necessary so that later it was not necessary to restart the search function by index if you need to work with reactive data

[Feature] allow complex key

function compareObjectVals (toCompareVals: [Object[], Object[]], key: string) :

currently - the matching of object is based on a "key" property.
this has a limitation for object with complex keys (multiple properties) - or where any other logic should be applied to find the match.

I suggest to extend the "key" parameter, so it allow passing a Matcher function. (but also allow passing a simple string - so you don't create breaking changes)
key: string | (left: any, right: any)=>bool

the library will check if the given key is a string or a function.
if its a string - the library will continue just like always - look for a property with the name of the key.
but if a function is given - the library will apply the function on 2 items to conclude if they "match".

lets say we have a Person object, and the key is based on firstName + lastName - we could write something like:

interface Person
{
   firstName: string;
   lastName: firstName;
   birthDate: Date;
   ...
}
compareObjectVals([arrBefore, arrAfter], (a, b) => a.firstName === b.firstName && a.lastName === b.lastName);

if it's fine by you - I can work on that a create a pull request.

[improvement] better key finding

you mentioned in an other issue, that you are opting for performance.

there is a big improvement you can do -
instead of declaring originalItemKeys and activeItemKeys as an array of keys, you can declare them as a regular objects (or es6 Set) - then, you don't need to use indexOf for checking if a key is already present. you decrease O(n) to O(1) for those checks.

if (i === originalItem.length - 1 && originalItemKeys.indexOf(activeItem[j][key]) === -1) {

if (activeItemKeys.indexOf(outerKeyVal) === -1) {

var originalItemKeys: any = {};
var activeItemKeys: any = {};

for (var i = 0; i < originalItem.length; i++) {
    var outerKeyVal = originalItem[i][key];
    originalItemKeys[outerKeyVal] = true;

    for (var j = 0; j < activeItem.length; j++) {
      if (i === 0) {
        activeItemKeys[activeItem[j][key]] = true;
      }

      if (i === originalItem.length - 1 && !originalItemKeys[activeItem[j][key]]) {
        createdVals.push(activeItem[j]);
      } else if (originalItem[i][key] === activeItem[j][key] && !isEqualObject(originalItem[i], activeItem[j])) {
        updatedVals.push(activeItem[j]);
      }
    }

    if (!activeItemKeys[outerKeyVal]) {
      deletedVals.push(originalItem[i]);
    }
  }

also: you referring a lot to originalItem[i] and [activeItem[j] - you should save them in a local variable.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.