实现效果
A javascript text differencing implementation.
译文:javascript文本差异实现。
相关文档
npm
npm install diff --save
CDN:
https://unpkg.com/diff@5.1.0/dist/diff.js
// CommonJS
// const Diff = require('diff')
// EMS
import * as Diff from 'diff'
const one = {
id: 1,
name: 'Tom',
age: 18,
}
const other = {
id: 2,
name: 'Jack',
age: 18,
}
const diff = Diff.diffJson(one, other)
console.log(diff);
输出
[
{ count: 2, value: '{\n "age": 18,\n' },
{
count: 2,
added: undefined,
removed: true,
value: ' "id": 1,\n "name": "Tom"\n'
},
{
count: 2,
added: true,
removed: undefined,
value: ' "id": 2,\n "name": "Jack"\n'
},
{ count: 1, value: '}' }
]
// const Diff = require('diff')
import * as Diff from 'diff'
const one = {
id: 1,
name: 'Tom',
age: 18,
}
const other = {
id: 2,
name: 'Jack',
age: 18,
}
const diff = Diff.diffLines(
JSON.stringify(one, null, 2),
JSON.stringify(other, null, 2)
)
console.log(diff)
输出
[
{ count: 1, value: '{\n' },
{
count: 2,
added: undefined,
removed: true,
value: ' "id": 1,\n "name": "Tom",\n'
},
{
count: 2,
added: true,
removed: undefined,
value: ' "id": 2,\n "name": "Jack",\n'
},
{ count: 2, value: ' "age": 18\n}' }
]
// const Diff = require('diff')
import * as Diff from 'diff'
const one = {
id: 1,
name: 'Tom',
age: 18,
}
const other = {
id: 2,
name: 'Jack',
age: 18,
}
const diff = Diff.diffArrays(
JSON.stringify(one, null, 2).split('\n'),
JSON.stringify(other, null, 2).split('\n'),
)
console.log(diff);
// 组装结果
let list = diff.map((part) => {
if (part.added) {
return part.value.map(x=>'+' + x).join('\n')
} else if (part.removed) {
return part.value.map(x=>'-' + x).join('\n')
} else {
return part.value.join('\n')
}
})
console.log(list.join('\n'))
输出
[
{ count: 1, value: [ '{' ] },
{
count: 2,
added: undefined,
removed: true,
value: [ ' "id": 1,', ' "name": "Tom",' ]
},
{
count: 2,
added: true,
removed: undefined,
value: [ ' "id": 2,', ' "name": "Jack",' ]
},
{ count: 2, value: [ ' "age": 18', '}' ] }
]
组合后输出
{
- "id": 1,
- "name": "Tom",
+ "id": 2,
+ "name": "Jack",
"age": 18
}
通过以上示例可以发现: