UNPKG

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