Advertisement
Guest User

Untitled

a guest
May 30th, 2015
239
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.02 KB | None | 0 0
  1. var deepDiffMapper = function() {
  2. return {
  3. VALUE_CREATED: 'created',
  4. VALUE_UPDATED: 'updated',
  5. VALUE_DELETED: 'deleted',
  6. VALUE_UNCHANGED: 'unchanged',
  7. map: function(obj1, obj2) {
  8. if (this.isFunction(obj1) || this.isFunction(obj2)) {
  9. throw 'Invalid argument. Function given, object expected.';
  10. }
  11. if (this.isValue(obj1) || this.isValue(obj2)) {
  12. return {type: this.compareValues(obj1, obj2), data: obj1 || obj2};
  13. }
  14.  
  15. var diff = {};
  16. for (var key in obj1) {
  17. if (this.isFunction(obj1[key])) {
  18. continue;
  19. }
  20.  
  21. var value2 = undefined;
  22. if ('undefined' != typeof(obj2[key])) {
  23. value2 = obj2[key];
  24. }
  25.  
  26. diff[key] = this.map(obj1[key], value2);
  27. }
  28. for (var key in obj2) {
  29. if (this.isFunction(obj2[key]) || ('undefined' != typeof(diff[key]))) {
  30. continue;
  31. }
  32.  
  33. diff[key] = this.map(undefined, obj2[key]);
  34. }
  35.  
  36. return diff;
  37.  
  38. },
  39. compareValues: function(value1, value2) {
  40. if (value1 === value2) {
  41. return this.VALUE_UNCHANGED;
  42. }
  43. if ('undefined' == typeof(value1)) {
  44. return this.VALUE_CREATED;
  45. }
  46. if ('undefined' == typeof(value2)) {
  47. return this.VALUE_DELETED;
  48. }
  49.  
  50. return this.VALUE_UPDATED;
  51. },
  52. isFunction: function(obj) {
  53. return {}.toString.apply(obj) === '[object Function]';
  54. },
  55. isArray: function(obj) {
  56. return {}.toString.apply(obj) === '[object Array]';
  57. },
  58. isObject: function(obj) {
  59. return {}.toString.apply(obj) === '[object Object]';
  60. },
  61. isValue: function(obj) {
  62. return !this.isObject(obj) && !this.isArray(obj);
  63. }
  64. }
  65. }();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement