Skip to content

Instantly share code, notes, and snippets.

@andrew-svirin
Last active November 14, 2019 13:38
Show Gist options
  • Save andrew-svirin/50e14f5537b968a17b63a2e9c44800e4 to your computer and use it in GitHub Desktop.
Save andrew-svirin/50e14f5537b968a17b63a2e9c44800e4 to your computer and use it in GitHub Desktop.
Exmple
/**
* Example ```javascript
* let objects = $.fn.findCreatedUpdatedDeleted(
* [{id:1, v:1}, {id:2, v:2}, {id:4, v:4}],
* [{id:null, v:3}, {id:2, v:3}, {id:4, v:5}],
* 'id',
* ['v'],
* 'new-'
* );
* console.log('result', objects);
* ```
*/
(function($) {
/**
* Find created, updated, deleted objects for 2 arrays of objects.
* @param oldObjects array - array of old objects
* @param newObjects array - array of new objects
* @param key string - uses for compare identical objects
* @param attributes array - uses for compare objects attributes
* @param newKeyPrefix string|null - prefix from that begins new object id
*/
$.fn.findCreatedUpdatedDeleted = function (oldObjects, newObjects, key, attributes, newKeyPrefix) {
let attributesLength = attributes.length, result = {};
result.created = newObjects.filter(function (newObject) {
if (null !== newKeyPrefix) {
return String(newObject[key]).startsWith(newKeyPrefix);
} else {
return null === newObject[key];
}
});
result.deleted = oldObjects.filter(function (oldObject) {
return -1 === newObjects.findIndex(function (newObject) {
return String(newObject[key]) === String(oldObject[key]);
});
});
result.updated = newObjects.filter(function (newObject) {
return -1 !== oldObjects.findIndex(function (oldObject) {
if (String(newObject[key]) === String(oldObject[key])) {
for (let i = 0; i < attributesLength; i++) {
if (newObject[attributes[i]] !== oldObject[attributes[i]]) {
return true;
}
}
}
return false;
});
});
return result;
};
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment