diff-ignoring-fun.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*jshint indent:2, laxcomma:true, laxbreak:true*/
  2. var util = require('util')
  3. , deep = require('..')
  4. ;
  5. function duckWalk() {
  6. util.log('right step, left-step, waddle');
  7. }
  8. function quadrapedWalk() {
  9. util.log('right hind-step, right fore-step, left hind-step, left fore-step');
  10. }
  11. var duck = {
  12. legs: 2,
  13. walk: duckWalk
  14. };
  15. var dog = {
  16. legs: 4,
  17. walk: quadrapedWalk
  18. };
  19. var diff = deep.diff(duck, dog);
  20. // The differences will include the legs, and walk.
  21. util.log('Differences:\r\n' + util.inspect(diff, false, 9));
  22. // To ignore behavioral differences (functions); use observableDiff and your own accumulator:
  23. var observed = [];
  24. deep.observableDiff(duck, dog, function (d) {
  25. if (d && d.lhs && typeof d.lhs !== 'function') {
  26. observed.push(d);
  27. }
  28. });
  29. util.log('Observed without recording functions:\r\n' + util.inspect(observed, false, 9));
  30. util.log(util.inspect(dog, false, 9) + ' walking: ');
  31. dog.walk();
  32. // The purpose of the observableDiff fn is to allow you to observe and apply differences
  33. // that make sense in your scenario...
  34. // We'll make the dog act like a duck...
  35. deep.observableDiff(dog, duck, function (d) {
  36. deep.applyChange(dog, duck, d);
  37. });
  38. util.log(util.inspect(dog, false, 9) + ' walking: ');
  39. dog.walk();
  40. // Now there are no differences between the duck and the dog:
  41. if (deep.diff(duck, dog)) {
  42. util.log("Ooops, that prior statement seems to be wrong! (but it won't be)");
  43. }
  44. // Now assign an "equivalent" walk function...
  45. dog.walk = function duckWalk() {
  46. util.log('right step, left-step, waddle');
  47. };
  48. if (diff = deep.diff(duck, dog)) {
  49. // The dog's walk function is an equivalent, but different duckWalk function.
  50. util.log('Hrmm, the dog walks differently: ' + util.inspect(diff, false, 9));
  51. }
  52. // Use the observableDiff fn to ingore based on behavioral equivalence...
  53. observed = [];
  54. deep.observableDiff(duck, dog, function (d) {
  55. // if the change is a function, only record it if the text of the fns differ:
  56. if (d && typeof d.lhs === 'function' && typeof d.rhs === 'function') {
  57. var leftFnText = d.lhs.toString();
  58. var rightFnText = d.rhs.toString();
  59. if (leftFnText !== rightFnText) {
  60. observed.push(d);
  61. }
  62. } else {
  63. observed.push(d);
  64. }
  65. });
  66. if (observed.length === 0) {
  67. util.log('Yay!, we detected that the walk functions are equivalent');
  68. }