-
Notifications
You must be signed in to change notification settings - Fork 9
/
util.js
52 lines (46 loc) · 1.11 KB
/
util.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
const jsdiff = require('diff')
const { ADD, DELETE } = require('./const')
class OldAction {
constructor (position, infos) {
this.position = position
this.infos = infos
}
}
const diff = function (oldStr, newStr) {
const parts = jsdiff.diffChars(oldStr, newStr)
let index = 0
const infosMap = new Map()
for (const p of parts) {
let infos = infosMap.get(index)
if (p.added === true || p.removed === true) {
switch (true) {
case p.added:
if (!infos) {
infos = []
infosMap.set(index, infos)
}
infos.push({ operat: ADD, chars: p.value })
break
case p.removed:
if (!infos) {
infos = []
infosMap.set(index + 1, infos)
}
infos.push({ operat: DELETE, chars: p.value })
break
default:
}
}
if (p.removed !== true) {
index = index + p.count
}
}
const oldActions = []
for (let [position, infos] of infosMap.entries()) {
oldActions.push(new OldAction(position, infos))
}
return oldActions
}
module.exports = {
diff
}