├── .circleci └── config.yml ├── .eslintrc ├── .gitignore ├── .npmignore ├── .vscode ├── launch.json └── tasks.json ├── ChangeLog.md ├── LICENSE ├── Readme.md ├── dist ├── deep-diff.min.js └── deep-diff.min.js.map ├── examples ├── apply-diff-from-any.js ├── array-change.js ├── capture_change_apply_elsewhere.js ├── diff-ignoring-fun.js ├── diff-scenarios.js ├── example1.js ├── issue-111.js ├── issue-113-1.js ├── issue-113-2.js ├── issue-115.js ├── issue-124.js ├── issue-125.js ├── issue-126.js ├── issue-35.js ├── issue-47.js ├── issue-48.js ├── issue-62.js ├── issue-70.js ├── issue-71.js ├── issue-72.js ├── issue-74.js ├── issue-78.js ├── issue-83.js ├── issue-88.js ├── performance.js └── practice-data.json ├── index.js ├── package-lock.json ├── package.json └── test ├── .eslintrc ├── tests.html └── tests.js /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | jobs: 3 | build: 4 | working_directory: ~/repo 5 | docker: 6 | - image: circleci/node:8.11.3 7 | steps: 8 | - checkout 9 | - run: 10 | name: authorize npm 11 | command: echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" >> ~/.npmrc 12 | - restore_cache: 13 | key: dependency-cache-{{ checksum "package.json" }} 14 | - run: 15 | name: run npm install 16 | command: npm install 17 | - save_cache: 18 | key: dependency-cache-{{ checksum "package.json" }} 19 | paths: 20 | - ./node_modules 21 | - run: mkdir ~/junit 22 | - run: 23 | name: build & test 24 | command: npm run ci 25 | when: always 26 | - run: cp test-results.xml ~/junit/test-results.xml 27 | - store_test_results: 28 | path: ~/junit 29 | - store_artifacts: 30 | path: ~/junit 31 | 32 | build_deploy_npm: 33 | working_directory: ~/repo 34 | docker: 35 | - image: circleci/node:8.11.3 36 | steps: 37 | - checkout 38 | - run: 39 | name: authorize npm 40 | command: echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" >> ~/.npmrc 41 | - restore_cache: 42 | key: dependency-cache-{{ checksum "package.json" }} 43 | - run: 44 | name: run npm install 45 | command: npm install 46 | - save_cache: 47 | key: dependency-cache-{{ checksum "package.json" }} 48 | paths: 49 | - ./node_modules 50 | - run: mkdir ~/junit 51 | - run: 52 | name: build & test 53 | command: npm run ci 54 | when: always 55 | - run: cp test-results.xml ~/junit/test-results.xml 56 | - store_test_results: 57 | path: ~/junit 58 | - store_artifacts: 59 | path: ~/junit 60 | - run: 61 | name: publish package to npm 62 | command: npm publish 63 | 64 | workflows: 65 | version: 2 66 | build_deploy: 67 | jobs: 68 | - build: 69 | context: secrets 70 | - build_deploy_npm: 71 | context: secrets 72 | filters: 73 | tags: 74 | only: /.*/ 75 | branches: 76 | ignore: /.*/ 77 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "parserOptions": { 3 | "sourceType": "module" 4 | }, 5 | "env": { 6 | "node": true, 7 | "browser": true 8 | }, 9 | "extends": "eslint:recommended", 10 | "rules": { 11 | "no-alert": 2, 12 | "no-array-constructor": 2, 13 | "no-caller": 2, 14 | "no-catch-shadow": 2, 15 | "no-eval": 2, 16 | "no-extend-native": 2, 17 | "no-extra-bind": 2, 18 | "no-implied-eval": 2, 19 | "no-iterator": 2, 20 | "no-label-var": 2, 21 | "no-labels": 2, 22 | "no-lone-blocks": 2, 23 | "no-loop-func": 2, 24 | "no-multi-spaces": 2, 25 | "no-multi-str": 2, 26 | "no-native-reassign": 2, 27 | "no-new": 2, 28 | "no-new-func": 2, 29 | "no-new-object": 2, 30 | "no-new-wrappers": 2, 31 | "no-octal-escape": 2, 32 | "no-process-exit": 2, 33 | "no-proto": 2, 34 | "no-return-assign": 2, 35 | "no-script-url": 2, 36 | "no-sequences": 2, 37 | "no-shadow": 2, 38 | "no-shadow-restricted-names": 2, 39 | "no-spaced-func": 2, 40 | "no-trailing-spaces": 2, 41 | "no-undef-init": 2, 42 | "no-underscore-dangle": 0, 43 | "no-unused-expressions": 2, 44 | "no-use-before-define": 2, 45 | "no-with": 2, 46 | "camelcase": 1, 47 | "comma-spacing": 2, 48 | "consistent-return": 2, 49 | "curly": [ 2, "all" ], 50 | "dot-notation": [ 2, { "allowKeywords": true } ], 51 | "eol-last": 2, 52 | "no-extra-parens": [ 2, "functions" ], 53 | "eqeqeq": 2, 54 | "keyword-spacing": [ 2, { "before": true, "after": true } ], 55 | "key-spacing": [ 2, { "beforeColon": false, "afterColon": true } ], 56 | "new-cap": 2, 57 | "new-parens": 2, 58 | "quotes": [ 2, "single" ], 59 | "semi": 2, 60 | "semi-spacing": [ 2, { "before": false, "after": true } ], 61 | "space-infix-ops": 2, 62 | "space-unary-ops": [ 2, { "words": true, "nonwords": false } ], 63 | "strict": [ 2, "global" ], 64 | "yoda": [ 2, "never" ] 65 | }, 66 | "overrides": [ 67 | { 68 | "files": [ "*.js", "test/*.js" ], 69 | "excludedFiles": "examples/*.js" 70 | } 71 | ] 72 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | coverage/ 3 | test-results.xml 4 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | test-results.xml -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "type": "node", 9 | "request": "launch", 10 | "name": "Launch Program", 11 | "program": "${workspaceFolder}/examples/array-change.js" 12 | }, 13 | { 14 | "name": "Run mocha", 15 | "type": "node", 16 | "request": "launch", 17 | "program": "${workspaceRoot}/node_modules/mocha/bin/_mocha", 18 | "stopOnEntry": false, 19 | "args": [ 20 | "test/**/*.js", 21 | "--no-timeouts" 22 | ], 23 | "cwd": "${workspaceRoot}", 24 | "runtimeExecutable": null, 25 | "env": { 26 | "NODE_ENV": "testing" 27 | } 28 | } 29 | ] 30 | } -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | // See https://go.microsoft.com/fwlink/?LinkId=733558 3 | // for the documentation about the tasks.json format 4 | "version": "2.0.0", 5 | "tasks": [ 6 | { 7 | "type": "npm", 8 | "script": "build", 9 | "problemMatcher": [] 10 | } 11 | ] 12 | } -------------------------------------------------------------------------------- /ChangeLog.md: -------------------------------------------------------------------------------- 1 | # deep-diff Change Log 2 | 3 | **deep-diff** is a javascript/node.js module providing utility functions for determining the structural differences between objects and includes some utilities for applying differences across objects. 4 | 5 | ## Log 6 | 7 | `1.0.2` - 2018-08-10 8 | 9 | * Support for react-native environment - Thanks @xanderberkein 10 | 11 | `1.0.0` - 2018-04-18 12 | 13 | * reverted to [UMD style module](https://github.com/umdjs/umd) rather than the ES6 style, which evidently, broke lots of people's previously working code. 14 | * fixed some bugs... see `examples/issue-XXx.js` for each issue I believe is fixed in this version. 15 | * Closed: 16 | * [#63 diff of equal objects should return empty array](https://github.com/flitbit/diff/issues/63) 17 | * [#115 Remove second argument of applyChange from public api](https://github.com/flitbit/diff/issues/115) 18 | * Resolved: 19 | * [#78 FeatureRequest: change the diff of array elements (or add such an option)](https://github.com/flitbit/diff/issues/78) 20 | * Fixed: 21 | * [#47 Deleting Array elements](https://github.com/flitbit/diff/issues/47) 22 | * [#111 Crash when comparing two undefined](https://github.com/flitbit/diff/issues/111) 23 | 24 | `0.3.8` - 2017-05-03 25 | 26 | * reconciled recently introduced difference between `index.es.js` and `index.js` 27 | * improved npm commands for more reliable contributions 28 | * added a few notes to README regarding contributing. 29 | 30 | `0.3.7` - 2017-05-01 31 | 32 | * fixed issue #98 by merging @sberan's pull request #99 — better handling of property with `undefined` value existing on either operand. Unit tests supplied. 33 | 34 | `0.3.6` - 2017-04-25 — Fixed, closed lingering issues: 35 | 36 | * fixed #74 — comparing objects with longer cycles 37 | * fixed #70 — was not properly detecting a deletion when a property on the operand (lhs) had a value of `undefined` and was _undefined_ on the comparand (rhs). :o). 38 | * WARNING! [Still broken when importing in Typescript](https://github.com/flitbit/diff/issues/97). 39 | 40 | `0.3.5` - 2017-04-23 — Rolled up recent fixes; patches: 41 | 42 | * @stevemao — #79, #80: now testing latest version of node4 43 | * @mortonfox — #85: referencing mocha's new home 44 | * @tdebarochez — #90: fixed error when .toString not a function 45 | * @thiamsantos — #92, #93: changed module system for improved es2015 modules. WARNING! [This PR broke importing `deep-diff` in Typescript as reported by @kgentes in #97](https://github.com/flitbit/diff/issues/97) 46 | 47 | `0.3.4` - Typescript users, reference this version until #97 is fixed! 48 | 49 | `0.3.3` - Thanks @SimenB: enabled npm script for release (alternate to the Makefile). Also linting as part of `npm test`. Thanks @joeldenning: Fixed issue #35; diffs of top level arrays now working. 50 | 51 | `0.3.3` - Thanks @SimenB: enabled npm script for release (alternate to the Makefile). Also linting as part of `npm test`. Thanks @joeldenning: Fixed issue #35; diffs of top level arrays now working. 52 | 53 | `0.3.2` - Resolves #46; support more robust filters by including `lhs` and `rhs` in the filter callback. By @Orlando80 54 | 55 | `0.3.1` - Better type checking by @Drinks, UMD wrapper by @SimenB. Now certifies against nodejs 12 and iojs (Thanks @SimenB). 56 | 57 | `0.2.0` - [Fixes Bug #17](https://github.com/flitbit/diff/issues/17), [Fixes Bug #19](https://github.com/flitbit/diff/issues/19), [Enhancement #21](https://github.com/flitbit/diff/issues/21) Applying changes that are properly structured can now be applied as a change (no longer requires typeof Diff) - supports differences being applied after round-trip serialization to JSON format. Prefilter now reports the path of all changes - it was not showing a path for arrays and anything in the structure below (reported by @ravishvt). 58 | 59 | *Breaking Change* – The structure of change records for differences below an array element has changed. Array indexes are now reported as numeric elements in the `path` if the changes is merely edited (an `E` kind). Changes of kind `A` (array) are only reported for changes in the terminal array itself and will have a nested `N` (new) item or a nested `D` (deleted) item. 60 | 61 | `0.1.7` - [Enhancement #11](https://github.com/flitbit/diff/issues/11) Added the ability to filter properties that should not be analyzed while calculating differences. Makes `deep-diff` more usable with frameworks that attach housekeeping properties to existing objects. AngularJS does this, and the new filter ability should ease working with it. 62 | 63 | `0.1.6` - Changed objects within nested arrays can now be applied. They were previously recording the changes appropriately but `applyDiff` would error. Comparison of `NaN` works more sanely - comparison to number shows difference, comparison to another `Nan` does not. -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2011-2018 Phillip Clark 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /Readme.md: -------------------------------------------------------------------------------- 1 | # deep-diff 2 | 3 | [![CircleCI](https://circleci.com/gh/flitbit/diff.svg?style=svg)](https://circleci.com/gh/flitbit/diff) 4 | 5 | [![NPM](https://nodei.co/npm/deep-diff.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/deep-diff/) 6 | 7 | **deep-diff** is a javascript/node.js module providing utility functions for determining the structural differences between objects and includes some utilities for applying differences across objects. 8 | 9 | ## Install 10 | 11 | ```bash 12 | npm install deep-diff 13 | ``` 14 | 15 | Possible v1.0.0 incompatabilities: 16 | 17 | * elements in arrays are now processed in reverse order, which fixes a few nagging bugs but may break some users 18 | * If your code relied on the order in which the differences were reported then your code will break. If you consider an object graph to be a big tree, then `deep-diff` does a [pre-order traversal of the object graph](https://en.wikipedia.org/wiki/Tree_traversal), however, when it encounters an array, the array is processed from the end towards the front, with each element recursively processed in-order during further descent. 19 | 20 | ## Features 21 | 22 | * Get the structural differences between two objects. 23 | * Observe the structural differences between two objects. 24 | * When structural differences represent change, apply change from one object to another. 25 | * When structural differences represent change, selectively apply change from one object to another. 26 | 27 | ## Installation 28 | 29 | ```bash 30 | npm install deep-diff 31 | ``` 32 | 33 | ### Importing 34 | 35 | #### nodejs 36 | 37 | ```javascript 38 | var diff = require('deep-diff') 39 | // or: 40 | // const diff = require('deep-diff'); 41 | // const { diff } = require('deep-diff'); 42 | // or: 43 | // const DeepDiff = require('deep-diff'); 44 | // const { DeepDiff } = require('deep-diff'); 45 | // es6+: 46 | // import diff from 'deep-diff'; 47 | // import { diff } from 'deep-diff'; 48 | // es6+: 49 | // import DeepDiff from 'deep-diff'; 50 | // import { DeepDiff } from 'deep-diff'; 51 | ``` 52 | 53 | #### browser 54 | 55 | ```html 56 | 57 | ``` 58 | 59 | > In a browser, `deep-diff` defines a global variable `DeepDiff`. If there is a conflict in the global namespace you can restore the conflicting definition and assign `deep-diff` to another variable like this: `var deep = DeepDiff.noConflict();`. 60 | 61 | ## Simple Examples 62 | 63 | In order to describe differences, change revolves around an `origin` object. For consistency, the `origin` object is always the operand on the `left-hand-side` of operations. The `comparand`, which may contain changes, is always on the `right-hand-side` of operations. 64 | 65 | ``` javascript 66 | var diff = require('deep-diff').diff; 67 | 68 | var lhs = { 69 | name: 'my object', 70 | description: 'it\'s an object!', 71 | details: { 72 | it: 'has', 73 | an: 'array', 74 | with: ['a', 'few', 'elements'] 75 | } 76 | }; 77 | 78 | var rhs = { 79 | name: 'updated object', 80 | description: 'it\'s an object!', 81 | details: { 82 | it: 'has', 83 | an: 'array', 84 | with: ['a', 'few', 'more', 'elements', { than: 'before' }] 85 | } 86 | }; 87 | 88 | var differences = diff(lhs, rhs); 89 | ``` 90 | 91 | *v 0.2.0 and above* The code snippet above would result in the following structure describing the differences: 92 | 93 | ``` javascript 94 | [ { kind: 'E', 95 | path: [ 'name' ], 96 | lhs: 'my object', 97 | rhs: 'updated object' }, 98 | { kind: 'E', 99 | path: [ 'details', 'with', 2 ], 100 | lhs: 'elements', 101 | rhs: 'more' }, 102 | { kind: 'A', 103 | path: [ 'details', 'with' ], 104 | index: 3, 105 | item: { kind: 'N', rhs: 'elements' } }, 106 | { kind: 'A', 107 | path: [ 'details', 'with' ], 108 | index: 4, 109 | item: { kind: 'N', rhs: { than: 'before' } } } ] 110 | ``` 111 | 112 | ### Differences 113 | 114 | Differences are reported as one or more change records. Change records have the following structure: 115 | 116 | * `kind` - indicates the kind of change; will be one of the following: 117 | * `N` - indicates a newly added property/element 118 | * `D` - indicates a property/element was deleted 119 | * `E` - indicates a property/element was edited 120 | * `A` - indicates a change occurred within an array 121 | * `path` - the property path (from the left-hand-side root) 122 | * `lhs` - the value on the left-hand-side of the comparison (undefined if kind === 'N') 123 | * `rhs` - the value on the right-hand-side of the comparison (undefined if kind === 'D') 124 | * `index` - when kind === 'A', indicates the array index where the change occurred 125 | * `item` - when kind === 'A', contains a nested change record indicating the change that occurred at the array index 126 | 127 | Change records are generated for all structural differences between `origin` and `comparand`. The methods only consider an object's own properties and array elements; those inherited from an object's prototype chain are not considered. 128 | 129 | Changes to arrays are recorded simplistically. We care most about the shape of the structure; therefore we don't take the time to determine if an object moved from one slot in the array to another. Instead, we only record the structural 130 | differences. If the structural differences are applied from the `comparand` to the `origin` then the two objects will compare as "deep equal" using most `isEqual` implementations such as found in [lodash](https://github.com/bestiejs/lodash) or [underscore](http://underscorejs.org/). 131 | 132 | ### Changes 133 | 134 | When two objects differ, you can observe the differences as they are calculated and selectively apply those changes to the origin object (left-hand-side). 135 | 136 | ``` javascript 137 | var observableDiff = require('deep-diff').observableDiff; 138 | var applyChange = require('deep-diff').applyChange; 139 | 140 | var lhs = { 141 | name: 'my object', 142 | description: 'it\'s an object!', 143 | details: { 144 | it: 'has', 145 | an: 'array', 146 | with: ['a', 'few', 'elements'] 147 | } 148 | }; 149 | 150 | var rhs = { 151 | name: 'updated object', 152 | description: 'it\'s an object!', 153 | details: { 154 | it: 'has', 155 | an: 'array', 156 | with: ['a', 'few', 'more', 'elements', { than: 'before' }] 157 | } 158 | }; 159 | 160 | observableDiff(lhs, rhs, function (d) { 161 | // Apply all changes except to the name property... 162 | if (d.path[d.path.length - 1] !== 'name') { 163 | applyChange(lhs, rhs, d); 164 | } 165 | }); 166 | ``` 167 | 168 | ## API Documentation 169 | 170 | A standard import of `var diff = require('deep-diff')` is assumed in all of the code examples. The import results in an object having the following public properties: 171 | 172 | * `diff(lhs, rhs[, options, acc])` — calculates the differences between two objects, optionally using the specified accumulator. 173 | * `observableDiff(lhs, rhs, observer[, options])` — calculates the differences between two objects and reports each to an observer function. 174 | * `applyDiff(target, source, filter)` — applies any structural differences from a source object to a target object, optionally filtering each difference. 175 | * `applyChange(target, source, change)` — applies a single change record to a target object. NOTE: `source` is unused and may be removed. 176 | * `revertChange(target, source, change)` reverts a single change record to a target object. NOTE: `source` is unused and may be removed. 177 | 178 | ### `diff` 179 | 180 | The `diff` function calculates the difference between two objects. 181 | 182 | 183 | #### Arguments 184 | 185 | * `lhs` - the left-hand operand; the origin object. 186 | * `rhs` - the right-hand operand; the object being compared structurally with the origin object. 187 | * `options` - A configuration object that can have the following properties: 188 | - `prefilter`: function that determines whether difference analysis should continue down the object graph. This function can also replace the `options` object in the parameters for backward compatibility. 189 | - `normalize`: function that pre-processes every _leaf_ of the tree. 190 | * `acc` - an optional accumulator/array (requirement is that it have a `push` function). Each difference is pushed to the specified accumulator. 191 | 192 | Returns either an array of changes or, if there are no changes, `undefined`. This was originally chosen so the result would be pass a truthy test: 193 | 194 | ```javascript 195 | var changes = diff(obja, objb); 196 | if (changes) { 197 | // do something with the changes. 198 | } 199 | ``` 200 | 201 | #### Pre-filtering Object Properties 202 | 203 | The `prefilter`'s signature should be `function(path, key)` and it should return a truthy value for any `path`-`key` combination that should be filtered. If filtered, the difference analysis does no further analysis of on the identified object-property path. 204 | 205 | ```javascript 206 | const diff = require('deep-diff'); 207 | const assert = require('assert'); 208 | 209 | const data = { 210 | issue: 126, 211 | submittedBy: 'abuzarhamza', 212 | title: 'readme.md need some additional example prefilter', 213 | posts: [ 214 | { 215 | date: '2018-04-16', 216 | text: `additional example for prefilter for deep-diff would be great. 217 | https://stackoverflow.com/questions/38364639/pre-filter-condition-deep-diff-node-js` 218 | } 219 | ] 220 | }; 221 | 222 | const clone = JSON.parse(JSON.stringify(data)); 223 | clone.title = 'README.MD needs additional example illustrating how to prefilter'; 224 | clone.disposition = 'completed'; 225 | 226 | const two = diff(data, clone); 227 | const none = diff(data, clone, 228 | (path, key) => path.length === 0 && ~['title', 'disposition'].indexOf(key) 229 | ); 230 | 231 | assert.equal(two.length, 2, 'should reflect two differences'); 232 | assert.ok(typeof none === 'undefined', 'should reflect no differences'); 233 | ``` 234 | #### Normalizing object properties 235 | 236 | The `normalize`'s signature should be `function(path, key, lhs, rhs)` and it should return either a falsy value if no normalization has occured, or a `[lhs, rhs]` array to replace the original values. This step doesn't occur if the path was filtered out in the `prefilter` phase. 237 | 238 | ```javascript 239 | const diff = require('deep-diff'); 240 | const assert = require('assert'); 241 | 242 | const data = { 243 | pull: 149, 244 | submittedBy: 'saveman71', 245 | }; 246 | 247 | const clone = JSON.parse(JSON.stringify(data)); 248 | clone.issue = 42; 249 | 250 | const two = diff(data, clone); 251 | const none = diff(data, clone, { 252 | normalize: (path, key, lhs, rhs) => { 253 | if (lhs === 149) { 254 | lhs = 42; 255 | } 256 | if (rhs === 149) { 257 | rhs = 42; 258 | } 259 | return [lsh, rhs]; 260 | } 261 | }); 262 | 263 | assert.equal(two.length, 1, 'should reflect one difference'); 264 | assert.ok(typeof none === 'undefined', 'should reflect no difference'); 265 | ``` 266 | 267 | ### `observableDiff` 268 | 269 | The `observableDiff` function calculates the difference between two objects and reports each to an observer function. 270 | 271 | #### Argmuments 272 | 273 | * `lhs` - the left-hand operand; the origin object. 274 | * `rhs` - the right-hand operand; the object being compared structurally with the origin object. 275 | * `observer` - The observer to report to. 276 | * `options` - A configuration object that can have the following properties: 277 | - `prefilter`: function that determines whether difference analysis should continue down the object graph. This function can also replace the `options` object in the parameters for backward compatibility. 278 | - `normalize`: function that pre-processes every _leaf_ of the tree. 279 | 280 | ## Contributing 281 | 282 | When contributing, keep in mind that it is an objective of `deep-diff` to have no package dependencies. This may change in the future, but for now, no-dependencies. 283 | 284 | Please run the unit tests before submitting your PR: `npm test`. Hopefully your PR includes additional unit tests to illustrate your change/modification! 285 | 286 | When you run `npm test`, linting will be performed and any linting errors will fail the tests... this includes code formatting. 287 | 288 | > Thanks to all those who have contributed so far! 289 | -------------------------------------------------------------------------------- /dist/deep-diff.min.js: -------------------------------------------------------------------------------- 1 | !function(e,t){var n=function(e){var l=["N","E","A","D"];function t(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}function n(e,t){Object.defineProperty(this,"kind",{value:e,enumerable:!0}),t&&t.length&&Object.defineProperty(this,"path",{value:t,enumerable:!0})}function D(e,t,n){D.super_.call(this,"E",e),Object.defineProperty(this,"lhs",{value:t,enumerable:!0}),Object.defineProperty(this,"rhs",{value:n,enumerable:!0})}function k(e,t){k.super_.call(this,"N",e),Object.defineProperty(this,"rhs",{value:t,enumerable:!0})}function j(e,t){j.super_.call(this,"D",e),Object.defineProperty(this,"lhs",{value:t,enumerable:!0})}function O(e,t,n){O.super_.call(this,"A",e),Object.defineProperty(this,"index",{value:t,enumerable:!0}),Object.defineProperty(this,"item",{value:n,enumerable:!0})}function f(e,t,n){var r=e.slice((n||t)+1||e.length);return e.length=t<0?e.length+t:t,e.push.apply(e,r),e}function w(e){var t=typeof e;return"object"!==t?t:e===Math?"math":null===e?"null":Array.isArray(e)?"array":"[object Date]"===Object.prototype.toString.call(e)?"date":"function"==typeof e.toString&&/^\/.*\//.test(e.toString())?"regexp":"object"}function u(e){var t=0;if(0===e.length)return t;for(var n=0;n Phase2 25 | 'id': 'Phase2', 26 | 'tasks': [ 27 | { 'id': 'Task3' } 28 | ] 29 | }, { 30 | 'id': 'Phase1', 31 | 'tasks': [ 32 | { 'id': 'Task1' }, 33 | { 'id': 'Task2' } 34 | ] 35 | }] 36 | }; 37 | 38 | var diff = deep.diff(lhs, rhs); 39 | console.log(util.inspect(diff, false, 9)); // eslint-disable-line no-console 40 | 41 | deep.applyDiff(lhs, rhs); 42 | console.log(util.inspect(lhs, false, 9)); // eslint-disable-line no-console 43 | 44 | expect(lhs).to.be.eql(rhs); 45 | 46 | -------------------------------------------------------------------------------- /examples/capture_change_apply_elsewhere.js: -------------------------------------------------------------------------------- 1 | /*jshint indent:2, laxcomma:true, laxbreak:true*/ 2 | var util = require('util') 3 | , assert = require('assert') 4 | , diff = require('..') 5 | , data = require('./practice-data') 6 | ; 7 | 8 | var i = Math.floor(Math.random() * data.length) + 1; 9 | var j = Math.floor(Math.random() * data.length) + 1; 10 | 11 | while (j === i) { 12 | j = Math.floor(Math.random() * data.length) + 1; 13 | } 14 | 15 | var source = data[i]; 16 | var comparand = data[j]; 17 | 18 | // source and comparand are different objects 19 | assert.notEqual(source, comparand); 20 | 21 | // source and comparand have differences in their structure 22 | assert.notDeepEqual(source, comparand); 23 | 24 | // record the differences between source and comparand 25 | var changes = diff(source, comparand); 26 | 27 | // apply the changes to the source 28 | changes.forEach(function (change) { 29 | diff.applyChange(source, true, change); 30 | }); 31 | 32 | // source and copmarand are now deep equal 33 | assert.deepEqual(source, comparand); 34 | 35 | // Simulate serializing to a remote copy of the object (we've already go a copy, copy the changes)... 36 | 37 | var remote = JSON.parse(JSON.stringify(source)); 38 | var remoteChanges = JSON.parse(JSON.stringify(changes)); 39 | 40 | // source and remote are different objects 41 | assert.notEqual(source, remote); 42 | 43 | // changes and remote changes are different objects 44 | assert.notEqual(changes, remoteChanges); 45 | 46 | // remote and comparand are different objects 47 | assert.notEqual(remote, comparand); 48 | 49 | remoteChanges.forEach(function (change) { 50 | diff.applyChange(remote, true, change); 51 | }); 52 | 53 | assert.deepEqual(remote, comparand); 54 | -------------------------------------------------------------------------------- /examples/diff-ignoring-fun.js: -------------------------------------------------------------------------------- 1 | /*jshint indent:2, laxcomma:true, laxbreak:true*/ 2 | var util = require('util') 3 | , deep = require('..') 4 | ; 5 | 6 | function duckWalk() { 7 | util.log('right step, left-step, waddle'); 8 | } 9 | 10 | function quadrapedWalk() { 11 | util.log('right hind-step, right fore-step, left hind-step, left fore-step'); 12 | } 13 | 14 | var duck = { 15 | legs: 2, 16 | walk: duckWalk 17 | }; 18 | 19 | var dog = { 20 | legs: 4, 21 | walk: quadrapedWalk 22 | }; 23 | 24 | var diff = deep.diff(duck, dog); 25 | 26 | // The differences will include the legs, and walk. 27 | util.log('Differences:\r\n' + util.inspect(diff, false, 9)); 28 | 29 | 30 | // To ignore behavioral differences (functions); use observableDiff and your own accumulator: 31 | 32 | var observed = []; 33 | deep.observableDiff(duck, dog, function (d) { 34 | if (d && d.lhs && typeof d.lhs !== 'function') { 35 | observed.push(d); 36 | } 37 | }); 38 | 39 | util.log('Observed without recording functions:\r\n' + util.inspect(observed, false, 9)); 40 | 41 | util.log(util.inspect(dog, false, 9) + ' walking: '); 42 | dog.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... 48 | deep.observableDiff(dog, duck, function (d) { 49 | deep.applyChange(dog, duck, d); 50 | }); 51 | 52 | util.log(util.inspect(dog, false, 9) + ' walking: '); 53 | dog.walk(); 54 | 55 | // Now there are no differences between the duck and the dog: 56 | if (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... 61 | dog.walk = function duckWalk() { 62 | util.log('right step, left-step, waddle'); 63 | }; 64 | 65 | if (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 | 72 | observed = []; 73 | deep.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 | 86 | if (observed.length === 0) { 87 | util.log('Yay!, we detected that the walk functions are equivalent'); 88 | } -------------------------------------------------------------------------------- /examples/diff-scenarios.js: -------------------------------------------------------------------------------- 1 | var util = require('util'), 2 | expect = require('expect.js'), 3 | eql = require('deep-equal'), 4 | deep = require('..') 5 | extend = util._extend; 6 | diff = deep.diff, 7 | apply = deep.applyDiff; 8 | 9 | function f0() {}; 10 | function f1() {}; 11 | 12 | var one = { it: 'be one', changed: false, with: { nested: 'data'}, f: f1}; 13 | var two = { it: 'be two', updated: true, changed: true, with: {nested: 'data', and: 'other', plus: one} }; 14 | var circ = {}; 15 | var other = { it: 'be other', numero: 34.29, changed: [ { it: 'is the same' }, 13.3, 'get some' ], with: {nested: 'reference', plus: circ} }; 16 | var circular = extend(circ, { it: 'be circ', updated: false, changed: [ { it: 'is not same' }, 13.3, 'get some!', {extra: 'stuff'}], with: { nested: 'reference', circular: other } }); 17 | 18 | util.log(util.inspect(diff(one, two), false, 99)); 19 | util.log(util.inspect(diff(two, one), false, 99)); 20 | 21 | util.log(util.inspect(diff(other, circular), false, 99)); 22 | 23 | var clone = extend({}, one); 24 | apply(clone, two); 25 | util.log(util.inspect(clone, false, 99)); 26 | 27 | expect(eql(clone, two)).to.be(true); 28 | expect(eql(clone, one)).to.be(false); 29 | 30 | clone = extend({}, circular); 31 | apply(clone, other); 32 | util.log(util.inspect(clone, false, 99)); 33 | expect(eql(clone, other)).to.be(true); 34 | expect(eql(clone, circular)).to.be(false); 35 | 36 | 37 | var array = { name: 'array two levels deep', item: { arr: ['it', { has: 'data' }]}}; 38 | var arrayChange = { name: 'array change two levels deep', item: { arr: ['it', { changes: 'data' }]}}; 39 | 40 | util.log(util.inspect(diff(array, arrayChange), false, 99)); 41 | clone = extend({}, array); 42 | apply(clone, arrayChange); 43 | util.log(util.inspect(clone, false, 99)); 44 | expect(eql(clone, arrayChange)).to.be(true); 45 | 46 | var one_prop = { one: 'property' }; 47 | var d = diff(one_prop, {}); 48 | expect(d.length).to.be(1); 49 | 50 | -------------------------------------------------------------------------------- /examples/example1.js: -------------------------------------------------------------------------------- 1 | var util = require('util') 2 | , deep = require('..') 3 | ; 4 | 5 | var lhs = { 6 | name: 'my object', 7 | description: 'it\'s an object!', 8 | details: { 9 | it: 'has', 10 | an: 'array', 11 | with: ['a', 'few', 'elements'] 12 | } 13 | }; 14 | 15 | var rhs = { 16 | name: 'updated object', 17 | description: 'it\'s an object!', 18 | details: { 19 | it: 'has', 20 | an: 'array', 21 | with: ['a', 'few', 'more', 'elements', { than: 'before' }] 22 | } 23 | }; 24 | 25 | var differences = deep.diff(lhs, rhs); 26 | 27 | // Print the differences to the console... 28 | util.log(util.inspect(differences, false, 99)); 29 | 30 | deep.observableDiff(lhs, rhs, function (d) { 31 | // Apply all changes except those to the 'name' property... 32 | if (d.path.length !== 1 || d.path.join('.') !== 'name') { 33 | deep.applyChange(lhs, rhs, d); 34 | } 35 | }, function (path, key) { 36 | var p = (path && path.length) ? path.join('/') : '' 37 | util.log('prefilter: path = ' + p + ' key = ' + key); 38 | } 39 | ); 40 | 41 | console.log(util.inspect(lhs, false, 99)); 42 | -------------------------------------------------------------------------------- /examples/issue-111.js: -------------------------------------------------------------------------------- 1 | var diff = require('../'); 2 | 3 | 4 | var differences = diff(undefined, undefined); 5 | // eslint-disable-next-line no-console 6 | console.log(differences); 7 | -------------------------------------------------------------------------------- /examples/issue-113-1.js: -------------------------------------------------------------------------------- 1 | const { log, inspect } = require('util'); 2 | const assert = require('assert'); 3 | const diff = require('../'); 4 | 5 | const o1 = {}; 6 | const o2 = {}; 7 | o1.foo = o1; 8 | o2.foo = o2; 9 | 10 | assert.notEqual(o1, o2, 'not same object'); 11 | assert.notEqual(o1.foo, o2.foo, 'not same object'); 12 | 13 | const differences = diff(o1, o2); 14 | log(inspect(differences, false, 9)); 15 | -------------------------------------------------------------------------------- /examples/issue-113-2.js: -------------------------------------------------------------------------------- 1 | const { log, inspect } = require('util'); 2 | const diff = require('../'); 3 | 4 | var o1 = {}; 5 | var o2 = {}; 6 | o1.foo = o1; 7 | o2.foo = {foo: o2}; 8 | const differences = diff(o1, o2); 9 | 10 | log(inspect(differences, false, 9)); 11 | 12 | -------------------------------------------------------------------------------- /examples/issue-115.js: -------------------------------------------------------------------------------- 1 | var diff = require('../'); 2 | var expect = require('expect.js'); 3 | 4 | var thing1 = 'this'; 5 | var thing2 = 'that'; 6 | var thing3 = 'other'; 7 | var thing4 = 'another'; 8 | 9 | var oldArray = [thing1, thing2, thing3, thing4]; 10 | var newArray = [thing1, thing2]; 11 | 12 | diff.observableDiff(oldArray, newArray, 13 | function (d) { 14 | diff.applyChange(oldArray, d); 15 | }); 16 | 17 | expect(oldArray).to.eql(newArray); 18 | -------------------------------------------------------------------------------- /examples/issue-124.js: -------------------------------------------------------------------------------- 1 | var diff = require('../'); 2 | 3 | var left = { key: [ {A: 0, B: 1}, {A: 2, B: 3} ] }; 4 | var right = { key: [ {A: 9, B: 1}, {A: 2, B: 3} ] }; 5 | 6 | var differences = diff(left, right); 7 | // eslint-disable-next-line no-console 8 | console.log(differences); 9 | -------------------------------------------------------------------------------- /examples/issue-125.js: -------------------------------------------------------------------------------- 1 | var diff = require('../'); 2 | 3 | const left = { 4 | nested: { 5 | param1: null, 6 | param2: null 7 | } 8 | }; 9 | 10 | const right = { 11 | nested: { 12 | param1: null, 13 | param2: null 14 | } 15 | }; 16 | 17 | var differences = diff(left, right); 18 | // eslint-disable-next-line no-console 19 | console.log(differences); 20 | -------------------------------------------------------------------------------- /examples/issue-126.js: -------------------------------------------------------------------------------- 1 | // This example shows how prefiltering can be used. 2 | 3 | const diff = require('../'); // deep-diff 4 | const { log, inspect } = require('util'); 5 | const assert = require('assert'); 6 | 7 | const data = { 8 | issue: 126, 9 | submittedBy: 'abuzarhamza', 10 | title: 'readme.md need some additional example prefilter', 11 | posts: [ 12 | { 13 | date: '2018-04-16', 14 | text: `additional example for prefilter for deep-diff would be great. 15 | https://stackoverflow.com/questions/38364639/pre-filter-condition-deep-diff-node-js` 16 | } 17 | ] 18 | }; 19 | 20 | const clone = JSON.parse(JSON.stringify(data)); 21 | clone.title = 'README.MD needs additional example illustrating how to prefilter'; 22 | clone.disposition = 'completed'; 23 | 24 | const two = diff(data, clone); 25 | const none = diff(data, clone, 26 | (path, key) => path.length === 0 && ~['title', 'disposition'].indexOf(key) 27 | ); 28 | 29 | assert.equal(two.length, 2, 'should reflect two differences'); 30 | assert.ok(typeof none === 'undefined', 'should reflect no differences'); 31 | 32 | log(inspect(two, false, 9)); 33 | log(inspect(none, false, 9)); 34 | -------------------------------------------------------------------------------- /examples/issue-35.js: -------------------------------------------------------------------------------- 1 | var deep = require('../'); 2 | 3 | var lhs = ['a', 'a']; 4 | var rhs = ['a']; 5 | var differences = deep.diff(lhs, rhs); 6 | differences.forEach(function (change) { 7 | deep.applyChange(lhs, true, change); 8 | }); 9 | 10 | console.log(lhs); // eslint-disable-line no-console 11 | console.log(rhs); // eslint-disable-line no-console 12 | -------------------------------------------------------------------------------- /examples/issue-47.js: -------------------------------------------------------------------------------- 1 | var diff = require('../'); 2 | var expect = require('expect.js'); 3 | 4 | var thing1 = 'this'; 5 | var thing2 = 'that'; 6 | var thing3 = 'other'; 7 | var thing4 = 'another'; 8 | 9 | var oldArray = [thing1, thing2, thing3, thing4]; 10 | var newArray = [thing1, thing2]; 11 | 12 | diff.observableDiff(oldArray, newArray, 13 | function (d) { 14 | diff.applyChange(oldArray, newArray, d); 15 | }); 16 | 17 | expect(oldArray).to.eql(newArray); 18 | -------------------------------------------------------------------------------- /examples/issue-48.js: -------------------------------------------------------------------------------- 1 | 2 | var dd = require('../'); // deep-diff 3 | var inspect = require('util').inspect; 4 | var expect = require('expect.js'); 5 | 6 | var before = { 7 | name: 'my object', 8 | description: 'it\'s an object!', 9 | details: { 10 | it: 'has', 11 | an: 'array', 12 | with: ['a', 'few', 'elements'] 13 | } 14 | }; 15 | 16 | var after = { 17 | name: 'updated object', 18 | description: 'it\'s an object!', 19 | details: { 20 | it: 'has', 21 | an: 'array', 22 | with: ['a', 'few', 'more', 'elements', { than: 'before' }] 23 | } 24 | }; 25 | 26 | var revertDiff = function (src, d) { 27 | d.forEach(function (change) { 28 | dd.revertChange(src, true, change); 29 | }); 30 | return src; 31 | }; 32 | 33 | var clone = function (src) { 34 | return JSON.parse(JSON.stringify(src)); 35 | }; 36 | 37 | var df = dd.diff(before, after); 38 | var b1 = clone(before); 39 | var a1 = clone(after); 40 | 41 | console.log(inspect(a1, false, 9)); // eslint-disable-line no-console 42 | 43 | var reverted = revertDiff(a1, df); 44 | console.log(inspect(reverted, false, 9)); // eslint-disable-line no-console 45 | console.log(inspect(b1, false, 9)); // eslint-disable-line no-console 46 | 47 | expect(reverted).to.eql(b1); 48 | 49 | -------------------------------------------------------------------------------- /examples/issue-62.js: -------------------------------------------------------------------------------- 1 | var deep = require("../"); 2 | 3 | // https://github.com/flitbit/diff/issues/62#issuecomment-229549984 4 | // 3: appears to be fixed, probably in fixing #74. 5 | 6 | var a = {}; 7 | var b = {}; 8 | a.x = b; 9 | b.x = b; 10 | deep.diff(a, b); // True 11 | 12 | a.x = a; // Change to a 13 | // No change to b 14 | console.log(deep.diff(a, b)); // Still true... 15 | -------------------------------------------------------------------------------- /examples/issue-70.js: -------------------------------------------------------------------------------- 1 | var deepDiff = require('../'); 2 | 3 | var left = {foo: undefined}; 4 | var right = {}; 5 | 6 | console.log(deepDiff.diff(left, right)); // eslint-disable-line no-console 7 | -------------------------------------------------------------------------------- /examples/issue-71.js: -------------------------------------------------------------------------------- 1 | var diff = require('../'); 2 | 3 | var left = { 4 | left: 'yes', 5 | right: 'no', 6 | }; 7 | 8 | var right = { 9 | left: { 10 | toString: true, 11 | }, 12 | right: 'no', 13 | }; 14 | 15 | console.log(diff(left, right)); // eslint-disable-line no-console 16 | -------------------------------------------------------------------------------- /examples/issue-72.js: -------------------------------------------------------------------------------- 1 | var diff = require('../'); 2 | 3 | var before = { 4 | data: [1, 2, 3] 5 | }; 6 | 7 | var after = { 8 | data: [4, 5, 1] 9 | }; 10 | 11 | var differences = diff(before, after); 12 | console.log(differences); // eslint-disable-line no-console 13 | differences.reduce( 14 | (acc, change) => { 15 | diff.revertChange(acc, true, change); 16 | return acc; 17 | }, 18 | after 19 | ); 20 | 21 | console.log(after); // eslint-disable-line no-console 22 | -------------------------------------------------------------------------------- /examples/issue-74.js: -------------------------------------------------------------------------------- 1 | var deepDiff = require("../"); 2 | 3 | var a = {prop: {}}; 4 | var b = {prop: {}}; 5 | 6 | a.prop.circ = a.prop; 7 | b.prop.circ = b; 8 | 9 | console.log(deepDiff.diff(a, b)); 10 | -------------------------------------------------------------------------------- /examples/issue-78.js: -------------------------------------------------------------------------------- 1 | 2 | const diff = require('../'); 3 | const ptr = require('json-ptr'); 4 | 5 | const inspect = require('util').inspect; 6 | 7 | 8 | const objA = { array: [{ a: 1 }] }; 9 | const objB = { array: [{ a: 2 }] }; 10 | 11 | let changes = diff(objA, objB); 12 | if (changes) { 13 | // decorate the changes using json-pointers 14 | for (let i = 0; i < changes.length; ++i) { 15 | let change = changes[i]; 16 | // get the parent path: 17 | let pointer = ptr.create(change.path.slice(0, change.path.length - 1)); 18 | if (change.kind === 'E') { 19 | change.elementLeft = pointer.get(objA); 20 | change.elementRight = pointer.get(objB); 21 | } 22 | } 23 | } 24 | console.log(inspect(changes, false, 9)); // eslint-disable-line no-console 25 | -------------------------------------------------------------------------------- /examples/issue-83.js: -------------------------------------------------------------------------------- 1 | var deepDiff = require("../"); 2 | 3 | var left = { 4 | date: null 5 | }; 6 | 7 | var right = { 8 | date: null 9 | }; 10 | 11 | console.log(deepDiff(left, right)); 12 | -------------------------------------------------------------------------------- /examples/issue-88.js: -------------------------------------------------------------------------------- 1 | var diff = require("../"); 2 | 3 | var before = { 4 | length: 3, 5 | data: [1, 2, 3] 6 | }; 7 | 8 | var after = { 9 | data: [4, 5, 1, 2, 3], 10 | count: 5 11 | }; 12 | 13 | var differences = diff(before, after); 14 | console.log(differences); 15 | 16 | function applyChanges(target, changes) { 17 | return changes.reduce( 18 | (acc, change) => { 19 | diff.applyChange(acc, true, change); 20 | return acc; 21 | }, 22 | target 23 | ); 24 | } 25 | 26 | console.log(applyChanges(before, differences)); 27 | -------------------------------------------------------------------------------- /examples/performance.js: -------------------------------------------------------------------------------- 1 | var util = require('util') 2 | , diff = require('..') 3 | , data = require('./practice-data') 4 | ; 5 | 6 | var cycle = -1 7 | , i 8 | , len = data.length 9 | , prior = {} 10 | , comparand 11 | , records 12 | , roll = [] 13 | , stat 14 | , stats = [] 15 | , mark, elapsed, avg = { diff: { ttl: 0 }, apply: { ttl: 0 } }, ttl = 0 16 | ; 17 | 18 | mark = process.hrtime(); 19 | while (++cycle < 10) { 20 | i = -1; 21 | while (++i < len) { 22 | stats.push(stat = { mark: process.hrtime() }); 23 | 24 | comparand = roll[i] || data[i]; 25 | 26 | stat.diff = { mark: process.hrtime() }; 27 | records = diff(prior, comparand); 28 | stat.diff.intv = process.hrtime(stat.diff.mark); 29 | 30 | if (records) { 31 | stat.apply = { count: diff.length, mark: process.hrtime() }; 32 | records.forEach(function (ch) { 33 | diff.applyChange(prior, comparand, ch); 34 | }); 35 | stat.apply.intv = process.hrtime(stat.apply.mark); 36 | 37 | prior = comparand; 38 | } 39 | stat.intv = process.hrtime(stat.mark); 40 | } 41 | } 42 | 43 | function ms(intv) { 44 | return (intv[0] * 1e9 + intv[1] / 1e6); 45 | } 46 | elapsed = ms(process.hrtime(mark)); 47 | 48 | stats.forEach(function (stat) { 49 | stat.elapsed = ms(stat.intv); 50 | stat.diff.elapsed = ms(stat.diff.intv); 51 | avg.diff.ttl += stat.diff.elapsed; 52 | if (stat.apply) { 53 | stat.apply.elapsed = ms(stat.apply.intv); 54 | ttl += stat.apply.count; 55 | avg.apply.ttl += stat.apply.elapsed; 56 | } 57 | }); 58 | 59 | avg.diff.avg = avg.diff.ttl / ttl; 60 | avg.apply.avg = avg.apply.ttl / ttl; 61 | 62 | console.log('Captured '.concat(stats.length, ' samples with ', ttl, ' combined differences in ', elapsed, 'ms')); 63 | console.log('\tavg diff: '.concat(avg.diff.avg, 'ms or ', (1 / avg.diff.avg), ' per ms')); 64 | console.log('\tavg apply: '.concat(avg.apply.avg, 'ms or ', (1 / avg.apply.avg), ' per ms')); 65 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | ;(function(root, factory) { // eslint-disable-line no-extra-semi 2 | var deepDiff = factory(root); 3 | // eslint-disable-next-line no-undef 4 | if (typeof define === 'function' && define.amd) { 5 | // AMD 6 | define('DeepDiff', function() { // eslint-disable-line no-undef 7 | return deepDiff; 8 | }); 9 | } else if (typeof exports === 'object' || typeof navigator === 'object' && navigator.product.match(/ReactNative/i)) { 10 | // Node.js or ReactNative 11 | module.exports = deepDiff; 12 | } else { 13 | // Browser globals 14 | var _deepdiff = root.DeepDiff; 15 | deepDiff.noConflict = function() { 16 | if (root.DeepDiff === deepDiff) { 17 | root.DeepDiff = _deepdiff; 18 | } 19 | return deepDiff; 20 | }; 21 | root.DeepDiff = deepDiff; 22 | } 23 | }(this, function(root) { 24 | var validKinds = ['N', 'E', 'A', 'D']; 25 | 26 | // nodejs compatible on server side and in the browser. 27 | function inherits(ctor, superCtor) { 28 | ctor.super_ = superCtor; 29 | ctor.prototype = Object.create(superCtor.prototype, { 30 | constructor: { 31 | value: ctor, 32 | enumerable: false, 33 | writable: true, 34 | configurable: true 35 | } 36 | }); 37 | } 38 | 39 | function Diff(kind, path) { 40 | Object.defineProperty(this, 'kind', { 41 | value: kind, 42 | enumerable: true 43 | }); 44 | if (path && path.length) { 45 | Object.defineProperty(this, 'path', { 46 | value: path, 47 | enumerable: true 48 | }); 49 | } 50 | } 51 | 52 | function DiffEdit(path, origin, value) { 53 | DiffEdit.super_.call(this, 'E', path); 54 | Object.defineProperty(this, 'lhs', { 55 | value: origin, 56 | enumerable: true 57 | }); 58 | Object.defineProperty(this, 'rhs', { 59 | value: value, 60 | enumerable: true 61 | }); 62 | } 63 | inherits(DiffEdit, Diff); 64 | 65 | function DiffNew(path, value) { 66 | DiffNew.super_.call(this, 'N', path); 67 | Object.defineProperty(this, 'rhs', { 68 | value: value, 69 | enumerable: true 70 | }); 71 | } 72 | inherits(DiffNew, Diff); 73 | 74 | function DiffDeleted(path, value) { 75 | DiffDeleted.super_.call(this, 'D', path); 76 | Object.defineProperty(this, 'lhs', { 77 | value: value, 78 | enumerable: true 79 | }); 80 | } 81 | inherits(DiffDeleted, Diff); 82 | 83 | function DiffArray(path, index, item) { 84 | DiffArray.super_.call(this, 'A', path); 85 | Object.defineProperty(this, 'index', { 86 | value: index, 87 | enumerable: true 88 | }); 89 | Object.defineProperty(this, 'item', { 90 | value: item, 91 | enumerable: true 92 | }); 93 | } 94 | inherits(DiffArray, Diff); 95 | 96 | function arrayRemove(arr, from, to) { 97 | var rest = arr.slice((to || from) + 1 || arr.length); 98 | arr.length = from < 0 ? arr.length + from : from; 99 | arr.push.apply(arr, rest); 100 | return arr; 101 | } 102 | 103 | function realTypeOf(subject) { 104 | var type = typeof subject; 105 | if (type !== 'object') { 106 | return type; 107 | } 108 | 109 | if (subject === Math) { 110 | return 'math'; 111 | } else if (subject === null) { 112 | return 'null'; 113 | } else if (Array.isArray(subject)) { 114 | return 'array'; 115 | } else if (Object.prototype.toString.call(subject) === '[object Date]') { 116 | return 'date'; 117 | } else if (typeof subject.toString === 'function' && /^\/.*\//.test(subject.toString())) { 118 | return 'regexp'; 119 | } 120 | return 'object'; 121 | } 122 | 123 | // http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/ 124 | function hashThisString(string) { 125 | var hash = 0; 126 | if (string.length === 0) { return hash; } 127 | for (var i = 0; i < string.length; i++) { 128 | var char = string.charCodeAt(i); 129 | hash = ((hash << 5) - hash) + char; 130 | hash = hash & hash; // Convert to 32bit integer 131 | } 132 | return hash; 133 | } 134 | 135 | // Gets a hash of the given object in an array order-independent fashion 136 | // also object key order independent (easier since they can be alphabetized) 137 | function getOrderIndependentHash(object) { 138 | var accum = 0; 139 | var type = realTypeOf(object); 140 | 141 | if (type === 'array') { 142 | object.forEach(function (item) { 143 | // Addition is commutative so this is order indep 144 | accum += getOrderIndependentHash(item); 145 | }); 146 | 147 | var arrayString = '[type: array, hash: ' + accum + ']'; 148 | return accum + hashThisString(arrayString); 149 | } 150 | 151 | if (type === 'object') { 152 | for (var key in object) { 153 | if (object.hasOwnProperty(key)) { 154 | var keyValueString = '[ type: object, key: ' + key + ', value hash: ' + getOrderIndependentHash(object[key]) + ']'; 155 | accum += hashThisString(keyValueString); 156 | } 157 | } 158 | 159 | return accum; 160 | } 161 | 162 | // Non object, non array...should be good? 163 | var stringToHash = '[ type: ' + type + ' ; value: ' + object + ']'; 164 | return accum + hashThisString(stringToHash); 165 | } 166 | 167 | function deepDiff(lhs, rhs, changes, prefilter, path, key, stack, orderIndependent) { 168 | changes = changes || []; 169 | path = path || []; 170 | stack = stack || []; 171 | var currentPath = path.slice(0); 172 | if (typeof key !== 'undefined' && key !== null) { 173 | if (prefilter) { 174 | if (typeof (prefilter) === 'function' && prefilter(currentPath, key)) { 175 | return; 176 | } else if (typeof (prefilter) === 'object') { 177 | if (prefilter.prefilter && prefilter.prefilter(currentPath, key)) { 178 | return; 179 | } 180 | if (prefilter.normalize) { 181 | var alt = prefilter.normalize(currentPath, key, lhs, rhs); 182 | if (alt) { 183 | lhs = alt[0]; 184 | rhs = alt[1]; 185 | } 186 | } 187 | } 188 | } 189 | currentPath.push(key); 190 | } 191 | 192 | // Use string comparison for regexes 193 | if (realTypeOf(lhs) === 'regexp' && realTypeOf(rhs) === 'regexp') { 194 | lhs = lhs.toString(); 195 | rhs = rhs.toString(); 196 | } 197 | 198 | var ltype = typeof lhs; 199 | var rtype = typeof rhs; 200 | var i, j, k, other; 201 | 202 | var ldefined = ltype !== 'undefined' || 203 | (stack && (stack.length > 0) && stack[stack.length - 1].lhs && 204 | Object.getOwnPropertyDescriptor(stack[stack.length - 1].lhs, key)); 205 | var rdefined = rtype !== 'undefined' || 206 | (stack && (stack.length > 0) && stack[stack.length - 1].rhs && 207 | Object.getOwnPropertyDescriptor(stack[stack.length - 1].rhs, key)); 208 | 209 | if (!ldefined && rdefined) { 210 | changes.push(new DiffNew(currentPath, rhs)); 211 | } else if (!rdefined && ldefined) { 212 | changes.push(new DiffDeleted(currentPath, lhs)); 213 | } else if (realTypeOf(lhs) !== realTypeOf(rhs)) { 214 | changes.push(new DiffEdit(currentPath, lhs, rhs)); 215 | } else if (realTypeOf(lhs) === 'date' && (lhs - rhs) !== 0) { 216 | changes.push(new DiffEdit(currentPath, lhs, rhs)); 217 | } else if (ltype === 'object' && lhs !== null && rhs !== null) { 218 | for (i = stack.length - 1; i > -1; --i) { 219 | if (stack[i].lhs === lhs) { 220 | other = true; 221 | break; 222 | } 223 | } 224 | if (!other) { 225 | stack.push({ lhs: lhs, rhs: rhs }); 226 | if (Array.isArray(lhs)) { 227 | // If order doesn't matter, we need to sort our arrays 228 | if (orderIndependent) { 229 | lhs.sort(function (a, b) { 230 | return getOrderIndependentHash(a) - getOrderIndependentHash(b); 231 | }); 232 | 233 | rhs.sort(function (a, b) { 234 | return getOrderIndependentHash(a) - getOrderIndependentHash(b); 235 | }); 236 | } 237 | i = rhs.length - 1; 238 | j = lhs.length - 1; 239 | while (i > j) { 240 | changes.push(new DiffArray(currentPath, i, new DiffNew(undefined, rhs[i--]))); 241 | } 242 | while (j > i) { 243 | changes.push(new DiffArray(currentPath, j, new DiffDeleted(undefined, lhs[j--]))); 244 | } 245 | for (; i >= 0; --i) { 246 | deepDiff(lhs[i], rhs[i], changes, prefilter, currentPath, i, stack, orderIndependent); 247 | } 248 | } else { 249 | var akeys = Object.keys(lhs).concat(Object.getOwnPropertySymbols(lhs)); 250 | var pkeys = Object.keys(rhs).concat(Object.getOwnPropertySymbols(rhs)); 251 | for (i = 0; i < akeys.length; ++i) { 252 | k = akeys[i]; 253 | other = pkeys.indexOf(k); 254 | if (other >= 0) { 255 | deepDiff(lhs[k], rhs[k], changes, prefilter, currentPath, k, stack, orderIndependent); 256 | pkeys[other] = null; 257 | } else { 258 | deepDiff(lhs[k], undefined, changes, prefilter, currentPath, k, stack, orderIndependent); 259 | } 260 | } 261 | for (i = 0; i < pkeys.length; ++i) { 262 | k = pkeys[i]; 263 | if (k) { 264 | deepDiff(undefined, rhs[k], changes, prefilter, currentPath, k, stack, orderIndependent); 265 | } 266 | } 267 | } 268 | stack.length = stack.length - 1; 269 | } else if (lhs !== rhs) { 270 | // lhs is contains a cycle at this element and it differs from rhs 271 | changes.push(new DiffEdit(currentPath, lhs, rhs)); 272 | } 273 | } else if (lhs !== rhs) { 274 | if (!(ltype === 'number' && isNaN(lhs) && isNaN(rhs))) { 275 | changes.push(new DiffEdit(currentPath, lhs, rhs)); 276 | } 277 | } 278 | } 279 | 280 | function observableDiff(lhs, rhs, observer, prefilter, orderIndependent) { 281 | var changes = []; 282 | deepDiff(lhs, rhs, changes, prefilter, null, null, null, orderIndependent); 283 | if (observer) { 284 | for (var i = 0; i < changes.length; ++i) { 285 | observer(changes[i]); 286 | } 287 | } 288 | return changes; 289 | } 290 | 291 | function orderIndependentDeepDiff(lhs, rhs, changes, prefilter, path, key, stack) { 292 | return deepDiff(lhs, rhs, changes, prefilter, path, key, stack, true); 293 | } 294 | 295 | function accumulateDiff(lhs, rhs, prefilter, accum) { 296 | var observer = (accum) ? 297 | function (difference) { 298 | if (difference) { 299 | accum.push(difference); 300 | } 301 | } : undefined; 302 | var changes = observableDiff(lhs, rhs, observer, prefilter); 303 | return (accum) ? accum : (changes.length) ? changes : undefined; 304 | } 305 | 306 | function accumulateOrderIndependentDiff(lhs, rhs, prefilter, accum) { 307 | var observer = (accum) ? 308 | function (difference) { 309 | if (difference) { 310 | accum.push(difference); 311 | } 312 | } : undefined; 313 | var changes = observableDiff(lhs, rhs, observer, prefilter, true); 314 | return (accum) ? accum : (changes.length) ? changes : undefined; 315 | } 316 | 317 | function applyArrayChange(arr, index, change) { 318 | if (change.path && change.path.length) { 319 | var it = arr[index], 320 | i, u = change.path.length - 1; 321 | for (i = 0; i < u; i++) { 322 | it = it[change.path[i]]; 323 | } 324 | switch (change.kind) { 325 | case 'A': 326 | applyArrayChange(it[change.path[i]], change.index, change.item); 327 | break; 328 | case 'D': 329 | delete it[change.path[i]]; 330 | break; 331 | case 'E': 332 | case 'N': 333 | it[change.path[i]] = change.rhs; 334 | break; 335 | } 336 | } else { 337 | switch (change.kind) { 338 | case 'A': 339 | applyArrayChange(arr[index], change.index, change.item); 340 | break; 341 | case 'D': 342 | arr = arrayRemove(arr, index); 343 | break; 344 | case 'E': 345 | case 'N': 346 | arr[index] = change.rhs; 347 | break; 348 | } 349 | } 350 | return arr; 351 | } 352 | 353 | function applyChange(target, source, change) { 354 | if (typeof change === 'undefined' && source && ~validKinds.indexOf(source.kind)) { 355 | change = source; 356 | } 357 | if (target && change && change.kind) { 358 | var it = target, 359 | i = -1, 360 | last = change.path ? change.path.length - 1 : 0; 361 | while (++i < last) { 362 | if (typeof it[change.path[i]] === 'undefined') { 363 | it[change.path[i]] = (typeof change.path[i + 1] !== 'undefined' && typeof change.path[i + 1] === 'number') ? [] : {}; 364 | } 365 | it = it[change.path[i]]; 366 | } 367 | switch (change.kind) { 368 | case 'A': 369 | if (change.path && typeof it[change.path[i]] === 'undefined') { 370 | it[change.path[i]] = []; 371 | } 372 | applyArrayChange(change.path ? it[change.path[i]] : it, change.index, change.item); 373 | break; 374 | case 'D': 375 | delete it[change.path[i]]; 376 | break; 377 | case 'E': 378 | case 'N': 379 | it[change.path[i]] = change.rhs; 380 | break; 381 | } 382 | } 383 | } 384 | 385 | function revertArrayChange(arr, index, change) { 386 | if (change.path && change.path.length) { 387 | // the structure of the object at the index has changed... 388 | var it = arr[index], 389 | i, u = change.path.length - 1; 390 | for (i = 0; i < u; i++) { 391 | it = it[change.path[i]]; 392 | } 393 | switch (change.kind) { 394 | case 'A': 395 | revertArrayChange(it[change.path[i]], change.index, change.item); 396 | break; 397 | case 'D': 398 | it[change.path[i]] = change.lhs; 399 | break; 400 | case 'E': 401 | it[change.path[i]] = change.lhs; 402 | break; 403 | case 'N': 404 | delete it[change.path[i]]; 405 | break; 406 | } 407 | } else { 408 | // the array item is different... 409 | switch (change.kind) { 410 | case 'A': 411 | revertArrayChange(arr[index], change.index, change.item); 412 | break; 413 | case 'D': 414 | arr[index] = change.lhs; 415 | break; 416 | case 'E': 417 | arr[index] = change.lhs; 418 | break; 419 | case 'N': 420 | arr = arrayRemove(arr, index); 421 | break; 422 | } 423 | } 424 | return arr; 425 | } 426 | 427 | function revertChange(target, source, change) { 428 | if (target && source && change && change.kind) { 429 | var it = target, 430 | i, u; 431 | u = change.path.length - 1; 432 | for (i = 0; i < u; i++) { 433 | if (typeof it[change.path[i]] === 'undefined') { 434 | it[change.path[i]] = {}; 435 | } 436 | it = it[change.path[i]]; 437 | } 438 | switch (change.kind) { 439 | case 'A': 440 | // Array was modified... 441 | // it will be an array... 442 | revertArrayChange(it[change.path[i]], change.index, change.item); 443 | break; 444 | case 'D': 445 | // Item was deleted... 446 | it[change.path[i]] = change.lhs; 447 | break; 448 | case 'E': 449 | // Item was edited... 450 | it[change.path[i]] = change.lhs; 451 | break; 452 | case 'N': 453 | // Item is new... 454 | delete it[change.path[i]]; 455 | break; 456 | } 457 | } 458 | } 459 | 460 | function applyDiff(target, source, filter) { 461 | if (target && source) { 462 | var onChange = function (change) { 463 | if (!filter || filter(target, source, change)) { 464 | applyChange(target, source, change); 465 | } 466 | }; 467 | observableDiff(target, source, onChange); 468 | } 469 | } 470 | 471 | Object.defineProperties(accumulateDiff, { 472 | 473 | diff: { 474 | value: accumulateDiff, 475 | enumerable: true 476 | }, 477 | orderIndependentDiff: { 478 | value: accumulateOrderIndependentDiff, 479 | enumerable: true 480 | }, 481 | observableDiff: { 482 | value: observableDiff, 483 | enumerable: true 484 | }, 485 | orderIndependentObservableDiff: { 486 | value: orderIndependentDeepDiff, 487 | enumerable: true 488 | }, 489 | orderIndepHash: { 490 | value: getOrderIndependentHash, 491 | enumerable: true 492 | }, 493 | applyDiff: { 494 | value: applyDiff, 495 | enumerable: true 496 | }, 497 | applyChange: { 498 | value: applyChange, 499 | enumerable: true 500 | }, 501 | revertChange: { 502 | value: revertChange, 503 | enumerable: true 504 | }, 505 | isConflict: { 506 | value: function () { 507 | return typeof $conflict !== 'undefined'; 508 | }, 509 | enumerable: true 510 | } 511 | }); 512 | 513 | // hackish... 514 | accumulateDiff.DeepDiff = accumulateDiff; 515 | // ...but works with: 516 | // import DeepDiff from 'deep-diff' 517 | // import { DeepDiff } from 'deep-diff' 518 | // const DeepDiff = require('deep-diff'); 519 | // const { DeepDiff } = require('deep-diff'); 520 | 521 | if (root) { 522 | root.DeepDiff = accumulateDiff; 523 | } 524 | 525 | return accumulateDiff; 526 | })); 527 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "deep-diff", 3 | "description": "Javascript utility for calculating deep difference, capturing changes, and applying changes across objects; for nodejs and the browser.", 4 | "version": "1.0.2", 5 | "license": "MIT", 6 | "keywords": [ 7 | "diff", 8 | "difference", 9 | "compare", 10 | "change-tracking" 11 | ], 12 | "author": "Phillip Clark ", 13 | "contributors": [ 14 | "Simen Bekkhus ", 15 | "Paul Pflugradt ", 16 | "wooorm ", 17 | "Nicholas Calugar ", 18 | "Yandell ", 19 | "Thiago Santos ", 20 | "Steve Mao ", 21 | "Mats Bryntse ", 22 | "Phillip Clark ", 23 | "ZauberNerd ", 24 | "ravishivt ", 25 | "Daniel Spangler ", 26 | "Sam Beran ", 27 | "Thomas de Barochez ", 28 | "Morton Fox ", 29 | "Amila Welihinda ", 30 | "Will Biddy ", 31 | "icesoar ", 32 | "Serkan Serttop ", 33 | "orlando ", 34 | "Tom MacWright ", 35 | "Denning ", 36 | "Dan Drinkard ", 37 | "Elad Efrat ", 38 | "caasi Huang ", 39 | "Tom Ashworth " 40 | ], 41 | "repository": { 42 | "type": "git", 43 | "url": "git://github.com/flitbit/diff.git" 44 | }, 45 | "main": "./index.js", 46 | "scripts": { 47 | "prerelease": "npm run clean && npm run test", 48 | "release": "uglifyjs -c -m -o dist/deep-diff.min.js --source-map -r '$,require,exports,self,module,define,navigator' index.js", 49 | "clean": "rimraf dist && mkdir dist", 50 | "preversion": "npm run release", 51 | "postversion": "git push && git push --tags", 52 | "pretest": "npm run lint", 53 | "test": "mocha test/**/*.js", 54 | "test:watch": "nodemon --ext js,json --ignore dist/ --exec 'npm test'", 55 | "preci": "npm run lint", 56 | "ci": "mocha --reporter mocha-junit-reporter test/**/*.js", 57 | "lint": "eslint index.js test" 58 | }, 59 | "devDependencies": { 60 | "bluebird": "^3.5.1", 61 | "deep-equal": "^1.0.1", 62 | "eslint": "^4.19.1", 63 | "eslint-plugin-mocha": "^5.0.0", 64 | "expect.js": "^0.3.1", 65 | "json": "^9.0.6", 66 | "json-ptr": "^1.1.0", 67 | "lodash": "^4.17.10", 68 | "mocha": "^5.1.1", 69 | "mocha-junit-reporter": "^1.17.0", 70 | "nodemon": "^1.17.4", 71 | "rimraf": "^2.6.2", 72 | "uglify-js": "^3.3.25" 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /test/.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "plugins": [ 3 | "mocha" 4 | ], 5 | "env": { 6 | "node": true, 7 | "mocha": true, 8 | "browser": true 9 | }, 10 | } -------------------------------------------------------------------------------- /test/tests.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Mocha Tests 6 | 7 | 8 | 9 | 10 | 11 |
12 | 16 | 17 | 18 | 19 | 22 | 23 | 24 | 25 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /test/tests.js: -------------------------------------------------------------------------------- 1 | (function (root, factory) { 2 | if (typeof define === 'function' && define.amd) { // eslint-disable-line no-undef 3 | define(['deep-diff', 'expect.js'], factory);// eslint-disable-line no-undef 4 | } else if (typeof module === 'object' && module.exports) { 5 | module.exports = factory(require('../'), require('expect.js')); 6 | } else { 7 | root.returnExports = factory(root.DeepDiff, root.expect); 8 | } 9 | // eslint-disable-next-line no-undef 10 | }(typeof self !== 'undefined' ? self : this, function (deep, expect) { 11 | 12 | describe('deep-diff', function () { 13 | var empty = {}; 14 | 15 | describe('A target that has no properties', function () { 16 | 17 | it('shows no differences when compared to another empty object', function () { 18 | expect(deep.diff(empty, {})).to.be.an('undefined'); 19 | }); 20 | 21 | describe('when compared to a different type of keyless object', function () { 22 | var comparandTuples = [ 23 | ['an array', { 24 | key: [] 25 | }], 26 | ['an object', { 27 | key: {} 28 | }], 29 | ['a date', { 30 | key: new Date() 31 | }], 32 | ['a null', { 33 | key: null 34 | }], 35 | ['a regexp literal', { 36 | key: /a/ 37 | }], 38 | ['Math', { 39 | key: Math 40 | }] 41 | ]; 42 | 43 | comparandTuples.forEach(function (lhsTuple) { 44 | comparandTuples.forEach(function (rhsTuple) { 45 | if (lhsTuple[0] === rhsTuple[0]) { 46 | return; 47 | } 48 | it('shows differences when comparing ' + lhsTuple[0] + ' to ' + rhsTuple[0], function () { 49 | var diff = deep.diff(lhsTuple[1], rhsTuple[1]); 50 | expect(diff).to.be.ok(); 51 | expect(diff.length).to.be(1); 52 | expect(diff[0]).to.have.property('kind'); 53 | expect(diff[0].kind).to.be('E'); 54 | }); 55 | }); 56 | }); 57 | }); 58 | 59 | describe('when compared with an object having other properties', function () { 60 | var comparand = { 61 | other: 'property', 62 | another: 13.13 63 | }; 64 | var diff = deep.diff(empty, comparand); 65 | 66 | it('the differences are reported', function () { 67 | expect(diff).to.be.ok(); 68 | expect(diff.length).to.be(2); 69 | 70 | expect(diff[0]).to.have.property('kind'); 71 | expect(diff[0].kind).to.be('N'); 72 | expect(diff[0]).to.have.property('path'); 73 | expect(diff[0].path).to.be.an(Array); 74 | expect(diff[0].path[0]).to.eql('other'); 75 | expect(diff[0]).to.have.property('rhs'); 76 | expect(diff[0].rhs).to.be('property'); 77 | 78 | expect(diff[1]).to.have.property('kind'); 79 | expect(diff[1].kind).to.be('N'); 80 | expect(diff[1]).to.have.property('path'); 81 | expect(diff[1].path).to.be.an(Array); 82 | expect(diff[1].path[0]).to.eql('another'); 83 | expect(diff[1]).to.have.property('rhs'); 84 | expect(diff[1].rhs).to.be(13.13); 85 | }); 86 | 87 | }); 88 | 89 | }); 90 | 91 | describe('A target that has one property', function () { 92 | var lhs = { 93 | one: 'property' 94 | }; 95 | 96 | it('shows no differences when compared to itself', function () { 97 | expect(deep.diff(lhs, lhs)).to.be.an('undefined'); 98 | }); 99 | 100 | it('shows the property as removed when compared to an empty object', function () { 101 | var diff = deep.diff(lhs, empty); 102 | expect(diff).to.be.ok(); 103 | expect(diff.length).to.be(1); 104 | expect(diff[0]).to.have.property('kind'); 105 | expect(diff[0].kind).to.be('D'); 106 | }); 107 | 108 | it('shows the property as edited when compared to an object with null', function () { 109 | var diff = deep.diff(lhs, { 110 | one: null 111 | }); 112 | expect(diff).to.be.ok(); 113 | expect(diff.length).to.be(1); 114 | expect(diff[0]).to.have.property('kind'); 115 | expect(diff[0].kind).to.be('E'); 116 | }); 117 | 118 | it('shows the property as edited when compared to an array', function () { 119 | var diff = deep.diff(lhs, ['one']); 120 | expect(diff).to.be.ok(); 121 | expect(diff.length).to.be(1); 122 | expect(diff[0]).to.have.property('kind'); 123 | expect(diff[0].kind).to.be('E'); 124 | }); 125 | 126 | }); 127 | 128 | describe('A target that has null value', function () { 129 | var lhs = { 130 | key: null 131 | }; 132 | 133 | it('shows no differences when compared to itself', function () { 134 | expect(deep.diff(lhs, lhs)).to.be.an('undefined'); 135 | }); 136 | 137 | it('shows the property as removed when compared to an empty object', function () { 138 | var diff = deep.diff(lhs, empty); 139 | expect(diff).to.be.ok(); 140 | expect(diff.length).to.be(1); 141 | expect(diff[0]).to.have.property('kind'); 142 | expect(diff[0].kind).to.be('D'); 143 | }); 144 | 145 | it('shows the property is changed when compared to an object that has value', function () { 146 | var diff = deep.diff(lhs, { 147 | key: 'value' 148 | }); 149 | expect(diff).to.be.ok(); 150 | expect(diff.length).to.be(1); 151 | expect(diff[0]).to.have.property('kind'); 152 | expect(diff[0].kind).to.be('E'); 153 | }); 154 | 155 | it('shows that an object property is changed when it is set to null', function () { 156 | lhs.key = { 157 | nested: 'value' 158 | }; 159 | var diff = deep.diff(lhs, { 160 | key: null 161 | }); 162 | expect(diff).to.be.ok(); 163 | expect(diff.length).to.be(1); 164 | expect(diff[0]).to.have.property('kind'); 165 | expect(diff[0].kind).to.be('E'); 166 | }); 167 | 168 | }); 169 | 170 | 171 | describe('A target that has a date value', function () { 172 | var lhs = { 173 | key: new Date(555555555555) 174 | }; 175 | 176 | it('shows the property is changed with a new date value', function () { 177 | var diff = deep.diff(lhs, { 178 | key: new Date(777777777777) 179 | }); 180 | expect(diff).to.be.ok(); 181 | expect(diff.length).to.be(1); 182 | expect(diff[0]).to.have.property('kind'); 183 | expect(diff[0].kind).to.be('E'); 184 | }); 185 | 186 | }); 187 | 188 | 189 | describe('A target that has a NaN', function () { 190 | var lhs = { 191 | key: NaN 192 | }; 193 | 194 | it('shows the property is changed when compared to another number', function () { 195 | var diff = deep.diff(lhs, { 196 | key: 0 197 | }); 198 | expect(diff).to.be.ok(); 199 | expect(diff.length).to.be(1); 200 | expect(diff[0]).to.have.property('kind'); 201 | expect(diff[0].kind).to.be('E'); 202 | }); 203 | 204 | it('shows no differences when compared to another NaN', function () { 205 | var diff = deep.diff(lhs, { 206 | key: NaN 207 | }); 208 | expect(diff).to.be.an('undefined'); 209 | }); 210 | 211 | }); 212 | 213 | 214 | describe('can revert namespace using noConflict', function () { 215 | if (deep.noConflict) { 216 | deep = deep.noConflict(); 217 | 218 | it('conflict is restored (when applicable)', function () { 219 | // In node there is no global conflict. 220 | if (typeof globalConflict !== 'undefined') { 221 | expect(DeepDiff).to.be(deep); // eslint-disable-line no-undef 222 | } 223 | }); 224 | 225 | it('DeepDiff functionality available through result of noConflict()', function () { 226 | expect(deep.applyDiff).to.be.a('function'); 227 | }); 228 | } 229 | }); 230 | 231 | 232 | describe('When filtering keys', function () { 233 | var lhs = { 234 | enhancement: 'Filter/Ignore Keys?', 235 | numero: 11, 236 | submittedBy: 'ericclemmons', 237 | supportedBy: ['ericclemmons'], 238 | status: 'open' 239 | }; 240 | var rhs = { 241 | enhancement: 'Filter/Ignore Keys?', 242 | numero: 11, 243 | submittedBy: 'ericclemmons', 244 | supportedBy: [ 245 | 'ericclemmons', 246 | 'TylerGarlick', 247 | 'flitbit', 248 | 'ergdev' 249 | ], 250 | status: 'closed', 251 | fixedBy: 'flitbit' 252 | }; 253 | 254 | describe('if the filtered property is an array', function () { 255 | 256 | it('changes to the array do not appear as a difference', function () { 257 | var prefilter = function (path, key) { 258 | return key === 'supportedBy'; 259 | }; 260 | var diff = deep(lhs, rhs, prefilter); 261 | expect(diff).to.be.ok(); 262 | expect(diff.length).to.be(2); 263 | expect(diff[0]).to.have.property('kind'); 264 | expect(diff[0].kind).to.be('E'); 265 | expect(diff[1]).to.have.property('kind'); 266 | expect(diff[1].kind).to.be('N'); 267 | }); 268 | 269 | }); 270 | 271 | describe('if the filtered config is passed as an object', function () { 272 | 273 | it('changes to the array to not appear as a difference', function () { 274 | var prefilter = function (path, key) { 275 | return key === 'supportedBy'; 276 | }; 277 | var diff = deep(lhs, rhs, {prefilter: prefilter}); 278 | expect(diff).to.be.ok(); 279 | expect(diff.length).to.be(2); 280 | expect(diff[0]).to.have.property('kind'); 281 | expect(diff[0].kind).to.be('E'); 282 | expect(diff[1]).to.have.property('kind'); 283 | expect(diff[1].kind).to.be('N'); 284 | }); 285 | 286 | }); 287 | 288 | describe('if the filtered property is not an array', function () { 289 | 290 | it('changes do not appear as a difference', function () { 291 | var prefilter = function (path, key) { 292 | return key === 'fixedBy'; 293 | }; 294 | var diff = deep(lhs, rhs, prefilter); 295 | expect(diff).to.be.ok(); 296 | expect(diff.length).to.be(4); 297 | expect(diff[0]).to.have.property('kind'); 298 | expect(diff[0].kind).to.be('A'); 299 | expect(diff[1]).to.have.property('kind'); 300 | expect(diff[1].kind).to.be('A'); 301 | expect(diff[2]).to.have.property('kind'); 302 | expect(diff[2].kind).to.be('A'); 303 | expect(diff[3]).to.have.property('kind'); 304 | expect(diff[3].kind).to.be('E'); 305 | }); 306 | 307 | }); 308 | }); 309 | 310 | describe('Can normalize properties to before diffing', function () { 311 | var testLHS = { 312 | array: [1, 2, 3, 4, 5], 313 | }; 314 | 315 | var testRHS = { 316 | array: '1/2/3/4/5', 317 | }; 318 | 319 | it('changes do not appear as a difference', function () { 320 | var filter = { 321 | normalize: function (path, key, lhs, rhs) { 322 | expect(key).to.be('array'); 323 | 324 | if (Array.isArray(lhs)) { 325 | lhs = lhs.join('/'); 326 | } 327 | if (Array.isArray(rhs)) { 328 | rhs = rhs.join('/'); 329 | } 330 | return [lhs, rhs]; 331 | } 332 | }; 333 | 334 | var diff; 335 | 336 | diff = deep(testLHS, testRHS, filter); 337 | expect(diff).to.be.an('undefined'); 338 | 339 | diff = deep(testRHS, testLHS, filter); 340 | expect(diff).to.be.an('undefined'); 341 | }); 342 | 343 | it('falsy return does not normalize', function () { 344 | var filter = { 345 | // eslint-disable-next-line no-unused-vars 346 | normalize: function (path, key, lhs, rhs) { 347 | return false; 348 | } 349 | }; 350 | 351 | var diff; 352 | 353 | diff = deep(testLHS, testRHS, filter); 354 | expect(diff).to.be.ok(); 355 | 356 | diff = deep(testRHS, testLHS, filter); 357 | expect(diff).to.be.ok(); 358 | }); 359 | }); 360 | 361 | describe('A target that has nested values', function () { 362 | var nestedOne = { 363 | noChange: 'same', 364 | levelOne: { 365 | levelTwo: 'value' 366 | }, 367 | arrayOne: [{ 368 | objValue: 'value' 369 | }] 370 | }; 371 | var nestedTwo = { 372 | noChange: 'same', 373 | levelOne: { 374 | levelTwo: 'another value' 375 | }, 376 | arrayOne: [{ 377 | objValue: 'new value' 378 | }, { 379 | objValue: 'more value' 380 | }] 381 | }; 382 | 383 | it('shows no differences when compared to itself', function () { 384 | expect(deep.diff(nestedOne, nestedOne)).to.be.an('undefined'); 385 | }); 386 | 387 | it('shows the property as removed when compared to an empty object', function () { 388 | var diff = deep(nestedOne, empty); 389 | expect(diff).to.be.ok(); 390 | expect(diff.length).to.be(3); 391 | expect(diff[0]).to.have.property('kind'); 392 | expect(diff[0].kind).to.be('D'); 393 | expect(diff[1]).to.have.property('kind'); 394 | expect(diff[1].kind).to.be('D'); 395 | }); 396 | 397 | it('shows the property is changed when compared to an object that has value', function () { 398 | var diff = deep.diff(nestedOne, nestedTwo); 399 | expect(diff).to.be.ok(); 400 | expect(diff.length).to.be(3); 401 | }); 402 | 403 | it('shows the property as added when compared to an empty object on left', function () { 404 | var diff = deep.diff(empty, nestedOne); 405 | expect(diff).to.be.ok(); 406 | expect(diff.length).to.be(3); 407 | expect(diff[0]).to.have.property('kind'); 408 | expect(diff[0].kind).to.be('N'); 409 | }); 410 | 411 | describe('when diff is applied to a different empty object', function () { 412 | var diff = deep.diff(nestedOne, nestedTwo); 413 | 414 | it('has result with nested values', function () { 415 | var result = {}; 416 | 417 | deep.applyChange(result, nestedTwo, diff[0]); 418 | expect(result.levelOne).to.be.ok(); 419 | expect(result.levelOne).to.be.an('object'); 420 | expect(result.levelOne.levelTwo).to.be.ok(); 421 | expect(result.levelOne.levelTwo).to.eql('another value'); 422 | }); 423 | 424 | it('has result with array object values', function () { 425 | var result = {}; 426 | 427 | deep.applyChange(result, nestedTwo, diff[2]); 428 | expect(result.arrayOne).to.be.ok(); 429 | expect(result.arrayOne).to.be.an('array'); 430 | expect(result.arrayOne[0]).to.be.ok(); 431 | expect(result.arrayOne[0].objValue).to.be.ok(); 432 | expect(result.arrayOne[0].objValue).to.equal('new value'); 433 | }); 434 | 435 | it('has result with added array objects', function () { 436 | var result = {}; 437 | 438 | deep.applyChange(result, nestedTwo, diff[1]); 439 | expect(result.arrayOne).to.be.ok(); 440 | expect(result.arrayOne).to.be.an('array'); 441 | expect(result.arrayOne[1]).to.be.ok(); 442 | expect(result.arrayOne[1].objValue).to.be.ok(); 443 | expect(result.arrayOne[1].objValue).to.equal('more value'); 444 | }); 445 | }); 446 | }); 447 | 448 | describe('regression test for bug #10, ', function () { 449 | var lhs = { 450 | id: 'Release', 451 | phases: [{ 452 | id: 'Phase1', 453 | tasks: [{ 454 | id: 'Task1' 455 | }, { 456 | id: 'Task2' 457 | }] 458 | }, { 459 | id: 'Phase2', 460 | tasks: [{ 461 | id: 'Task3' 462 | }] 463 | }] 464 | }; 465 | var rhs = { 466 | id: 'Release', 467 | phases: [{ 468 | // E: Phase1 -> Phase2 469 | id: 'Phase2', 470 | tasks: [{ 471 | id: 'Task3' 472 | }] 473 | }, { 474 | id: 'Phase1', 475 | tasks: [{ 476 | id: 'Task1' 477 | }, { 478 | id: 'Task2' 479 | }] 480 | }] 481 | }; 482 | 483 | describe('differences in nested arrays are detected', function () { 484 | var diff = deep.diff(lhs, rhs); 485 | 486 | // there should be differences 487 | expect(diff).to.be.ok(); 488 | expect(diff.length).to.be(6); 489 | 490 | it('differences can be applied', function () { 491 | var applied = deep.applyDiff(lhs, rhs); 492 | 493 | it('and the result equals the rhs', function () { 494 | expect(applied).to.eql(rhs); 495 | }); 496 | 497 | }); 498 | }); 499 | 500 | }); 501 | 502 | describe('regression test for bug #35', function () { 503 | var lhs = ['a', 'a', 'a']; 504 | var rhs = ['a']; 505 | 506 | it('can apply diffs between two top level arrays', function () { 507 | var differences = deep.diff(lhs, rhs); 508 | 509 | differences.forEach(function (it) { 510 | deep.applyChange(lhs, true, it); 511 | }); 512 | 513 | expect(lhs).to.eql(['a']); 514 | }); 515 | }); 516 | 517 | describe('Objects from different frames', function () { 518 | if (typeof globalConflict === 'undefined') { return; } 519 | 520 | // eslint-disable-next-line no-undef 521 | var frame = document.createElement('iframe'); 522 | // eslint-disable-next-line no-undef 523 | document.body.appendChild(frame); 524 | 525 | var lhs = new frame.contentWindow.Date(2010, 1, 1); 526 | var rhs = new frame.contentWindow.Date(2010, 1, 1); 527 | 528 | it('can compare date instances from a different frame', function () { 529 | var differences = deep.diff(lhs, rhs); 530 | 531 | expect(differences).to.be(undefined); 532 | }); 533 | }); 534 | 535 | describe('Comparing regexes should work', function () { 536 | var lhs = /foo/; 537 | var rhs = /foo/i; 538 | 539 | it('can compare regex instances', function () { 540 | var diff = deep.diff(lhs, rhs); 541 | 542 | expect(diff.length).to.be(1); 543 | 544 | expect(diff[0].kind).to.be('E'); 545 | expect(diff[0].path).to.not.be.ok(); 546 | expect(diff[0].lhs).to.be('/foo/'); 547 | expect(diff[0].rhs).to.be('/foo/i'); 548 | }); 549 | }); 550 | 551 | describe('subject.toString is not a function', function () { 552 | var lhs = { 553 | left: 'yes', 554 | right: 'no', 555 | }; 556 | var rhs = { 557 | left: { 558 | toString: true, 559 | }, 560 | right: 'no', 561 | }; 562 | 563 | it('should not throw a TypeError', function () { 564 | var diff = deep.diff(lhs, rhs); 565 | 566 | expect(diff.length).to.be(1); 567 | }); 568 | }); 569 | 570 | describe('regression test for issue #83', function () { 571 | var lhs = { 572 | date: null 573 | }; 574 | var rhs = { 575 | date: null 576 | }; 577 | 578 | it('should not detect a difference', function () { 579 | expect(deep.diff(lhs, rhs)).to.be(undefined); 580 | }); 581 | }); 582 | 583 | describe('regression test for issue #70', function () { 584 | 585 | it('should detect a difference with undefined property on lhs', function () { 586 | var diff = deep.diff({ foo: undefined }, {}); 587 | 588 | expect(diff).to.be.an(Array); 589 | expect(diff.length).to.be(1); 590 | 591 | expect(diff[0].kind).to.be('D'); 592 | expect(diff[0].path).to.be.an('array'); 593 | expect(diff[0].path).to.have.length(1); 594 | expect(diff[0].path[0]).to.be('foo'); 595 | expect(diff[0].lhs).to.be(undefined); 596 | 597 | }); 598 | 599 | it('should detect a difference with undefined property on rhs', function () { 600 | var diff = deep.diff({}, { foo: undefined }); 601 | 602 | expect(diff).to.be.an(Array); 603 | expect(diff.length).to.be(1); 604 | 605 | expect(diff[0].kind).to.be('N'); 606 | expect(diff[0].path).to.be.an('array'); 607 | expect(diff[0].path).to.have.length(1); 608 | expect(diff[0].path[0]).to.be('foo'); 609 | expect(diff[0].rhs).to.be(undefined); 610 | 611 | }); 612 | }); 613 | 614 | describe('regression test for issue #98', function () { 615 | var lhs = { foo: undefined }; 616 | var rhs = { foo: undefined }; 617 | 618 | it('should not detect a difference with two undefined property values', function () { 619 | var diff = deep.diff(lhs, rhs); 620 | 621 | expect(diff).to.be(undefined); 622 | 623 | }); 624 | }); 625 | 626 | describe('regression tests for issue #102', function () { 627 | it('should not throw a TypeError', function () { 628 | 629 | var diff = deep.diff(null, undefined); 630 | 631 | expect(diff).to.be.an(Array); 632 | expect(diff.length).to.be(1); 633 | 634 | expect(diff[0].kind).to.be('D'); 635 | expect(diff[0].lhs).to.be(null); 636 | 637 | }); 638 | 639 | it('should not throw a TypeError', function () { 640 | 641 | var diff = deep.diff(Object.create(null), { foo: undefined }); 642 | 643 | expect(diff).to.be.an(Array); 644 | expect(diff.length).to.be(1); 645 | 646 | expect(diff[0].kind).to.be('N'); 647 | expect(diff[0].rhs).to.be(undefined); 648 | }); 649 | }); 650 | 651 | describe('Order independent hash testing', function () { 652 | function sameHash(a, b) { 653 | expect(deep.orderIndepHash(a)).to.equal(deep.orderIndepHash(b)); 654 | } 655 | 656 | function differentHash(a, b) { 657 | expect(deep.orderIndepHash(a)).to.not.equal(deep.orderIndepHash(b)); 658 | } 659 | 660 | describe('Order indepdendent hash function should give different values for different objects', function () { 661 | it('should give different values for different "simple" types', function () { 662 | differentHash(1, -20); 663 | differentHash('foo', 45); 664 | differentHash('pie', 'something else'); 665 | differentHash(1.3332, 1); 666 | differentHash(1, null); 667 | differentHash('this is kind of a long string, don\'t you think?', 'the quick brown fox jumped over the lazy doge'); 668 | differentHash(true, 2); 669 | differentHash(false, 'flooog'); 670 | }); 671 | 672 | it('should give different values for string and object with string', function () { 673 | differentHash('some string', { key: 'some string' }); 674 | }); 675 | 676 | it('should give different values for number and array', function () { 677 | differentHash(1, [1]); 678 | }); 679 | 680 | it('should give different values for string and array of string', function () { 681 | differentHash('string', ['string']); 682 | }); 683 | 684 | it('should give different values for boolean and object with boolean', function () { 685 | differentHash(true, { key: true }); 686 | }); 687 | 688 | it('should give different values for different arrays', function () { 689 | differentHash([1, 2, 3], [1, 2]); 690 | differentHash([1, 4, 5, 6], ['foo', 1, true, undefined]); 691 | differentHash([1, 4, 6], [1, 4, 7]); 692 | differentHash([1, 3, 5], ['1', '3', '5']); 693 | }); 694 | 695 | it('should give different values for different objects', function () { 696 | differentHash({ key: 'value' }, { other: 'value' }); 697 | differentHash({ a: { b: 'c' } }, { a: 'b' }); 698 | }); 699 | 700 | it('should differentiate between arrays and objects', function () { 701 | differentHash([1, true, '1'], { a: 1, b: true, c: '1' }); 702 | }); 703 | }); 704 | 705 | describe('Order independent hash function should work in pathological cases', function () { 706 | it('should work in funky javascript cases', function () { 707 | differentHash(undefined, null); 708 | differentHash(0, undefined); 709 | differentHash(0, null); 710 | differentHash(0, false); 711 | differentHash(0, []); 712 | differentHash('', []); 713 | differentHash(3.22, '3.22'); 714 | differentHash(true, 'true'); 715 | differentHash(false, 0); 716 | }); 717 | 718 | it('should work on empty array and object', function () { 719 | differentHash([], {}); 720 | }); 721 | 722 | it('should work on empty object and undefined', function () { 723 | differentHash({}, undefined); 724 | }); 725 | 726 | it('should work on empty array and array with 0', function () { 727 | differentHash([], [0]); 728 | }); 729 | }); 730 | 731 | describe('Order independent hash function should be order independent', function () { 732 | it('should not care about array order', function () { 733 | sameHash([1, 2, 3], [3, 2, 1]); 734 | sameHash(['hi', true, 9.4], [true, 'hi', 9.4]); 735 | }); 736 | 737 | it('should not care about key order in an object', function () { 738 | sameHash({ foo: 'bar', foz: 'baz' }, { foz: 'baz', foo: 'bar' }); 739 | }); 740 | 741 | it('should work with complicated objects', function () { 742 | var obj1 = { 743 | foo: 'bar', 744 | faz: [ 745 | 1, 746 | 'pie', 747 | { 748 | food: 'yum' 749 | } 750 | ] 751 | }; 752 | 753 | var obj2 = { 754 | faz: [ 755 | 'pie', 756 | { 757 | food: 'yum' 758 | }, 759 | 1 760 | ], 761 | foo: 'bar' 762 | }; 763 | 764 | sameHash(obj1, obj2); 765 | }); 766 | }); 767 | }); 768 | 769 | 770 | describe('Order indepedent array comparison should work', function () { 771 | it('can compare simple arrays in an order independent fashion', function () { 772 | var lhs = [1, 2, 3]; 773 | var rhs = [1, 3, 2]; 774 | 775 | var diff = deep.orderIndependentDiff(lhs, rhs); 776 | expect(diff).to.be(undefined); 777 | }); 778 | 779 | it('still works with repeated elements', function () { 780 | var lhs = [1, 1, 2]; 781 | var rhs = [1, 2, 1]; 782 | 783 | var diff = deep.orderIndependentDiff(lhs, rhs); 784 | expect(diff).to.be(undefined); 785 | }); 786 | 787 | it('works on complex objects', function () { 788 | var obj1 = { 789 | foo: 'bar', 790 | faz: [ 791 | 1, 792 | 'pie', 793 | { 794 | food: 'yum' 795 | } 796 | ] 797 | }; 798 | 799 | var obj2 = { 800 | faz: [ 801 | 'pie', 802 | { 803 | food: 'yum' 804 | }, 805 | 1 806 | ], 807 | foo: 'bar' 808 | }; 809 | 810 | var diff = deep.orderIndependentDiff(obj1, obj2); 811 | expect(diff).to.be(undefined); 812 | }); 813 | 814 | it('should report some difference in non-equal arrays', function () { 815 | var lhs = [1, 2, 3]; 816 | var rhs = [2, 2, 3]; 817 | 818 | var diff = deep.orderIndependentDiff(lhs, rhs); 819 | expect(diff.length).to.be.ok(); 820 | }); 821 | 822 | 823 | }); 824 | 825 | }); 826 | 827 | describe('Diff-ing symbol-based keys should work', function () { 828 | const lhs = { 829 | [Symbol.iterator]: 'Iterator', // eslint-disable-line no-undef 830 | foo: 'bar' 831 | }; 832 | const rhs = { 833 | foo: 'baz' 834 | }; 835 | 836 | const res = deep.diff(lhs, rhs); 837 | expect(res).to.be.ok(); 838 | expect(res).to.be.an('array'); 839 | expect(res).to.have.length(2); 840 | 841 | let changed = 0, deleted = 0; 842 | for (const difference of res) { 843 | if (difference.kind === 'D') { 844 | deleted += 1; 845 | } else if (difference.kind === 'E') { 846 | changed += 1; 847 | } 848 | } 849 | 850 | expect(changed).to.be(1); 851 | expect(deleted).to.be(1); 852 | 853 | }); 854 | 855 | })); 856 | --------------------------------------------------------------------------------