@@ -13,69 +13,46 @@ export async function* streamDiff(
13
13
oldLines : string [ ] ,
14
14
newLines : LineStream ,
15
15
) : AsyncGenerator < DiffLine > {
16
+ const mutatedOldLines = [ ...oldLines ] ; // be careful
17
+
16
18
// If one indentation mistake is made, others are likely. So we are more permissive about matching
17
19
let seenIndentationMistake = false ;
18
20
19
21
let newLineResult = await newLines . next ( ) ;
20
-
21
22
while ( oldLines . length > 0 && ! newLineResult . done ) {
22
- const { matchIndex, isPerfectMatch, newLine } = matchLine (
23
+ const [ matchIndex , isPerfectMatch , newLine ] = matchLine (
23
24
newLineResult . value ,
24
25
oldLines ,
25
26
seenIndentationMistake ,
26
27
) ;
27
-
28
28
if ( ! seenIndentationMistake && newLineResult . value !== newLine ) {
29
29
seenIndentationMistake = true ;
30
30
}
31
31
32
- let type : DiffLine [ "type" ] ;
33
-
34
- let isLineRemoval = false ;
35
- const isNewLine = matchIndex === - 1 ;
36
-
37
- if ( isNewLine ) {
38
- type = "new" ;
32
+ if ( matchIndex < 0 ) {
33
+ // Insert new line
34
+ yield { type : "new" , line : newLine } ;
39
35
} else {
40
36
// Insert all deleted lines before match
41
37
for ( let i = 0 ; i < matchIndex ; i ++ ) {
42
38
yield { type : "old" , line : oldLines . shift ( ) ! } ;
43
39
}
44
40
45
- type = isPerfectMatch ? "same" : "old" ;
46
- }
47
-
48
- switch ( type ) {
49
- case "new" :
50
- yield { type, line : newLine } ;
51
- break ;
52
-
53
- case "same" :
54
- yield { type, line : oldLines . shift ( ) ! } ;
55
- break ;
56
-
57
- case "old" :
58
- yield { type, line : oldLines . shift ( ) ! } ;
59
-
60
- if ( oldLines [ 0 ] !== newLine ) {
61
- yield { type : "new" , line : newLine } ;
62
- } else {
63
- isLineRemoval = true ;
64
- }
65
-
66
- break ;
67
-
68
- default :
69
- console . error ( `Error streaming diff, unrecognized diff type: ${ type } ` ) ;
41
+ if ( isPerfectMatch ) {
42
+ // Same
43
+ yield { type : "same" , line : oldLines . shift ( ) ! } ;
44
+ } else {
45
+ // Delete old line and insert the new
46
+ yield { type : "old" , line : oldLines . shift ( ) ! } ;
47
+ yield { type : "new" , line : newLine } ;
48
+ }
70
49
}
71
50
72
- if ( ! isLineRemoval ) {
73
- newLineResult = await newLines . next ( ) ;
74
- }
51
+ newLineResult = await newLines . next ( ) ;
75
52
}
76
53
77
54
// Once at the edge, only one choice
78
- if ( newLineResult . done && oldLines . length > 0 ) {
55
+ if ( newLineResult . done === true && oldLines . length > 0 ) {
79
56
for ( const oldLine of oldLines ) {
80
57
yield { type : "old" , line : oldLine } ;
81
58
}
@@ -87,4 +64,4 @@ export async function* streamDiff(
87
64
yield { type : "new" , line : newLine } ;
88
65
}
89
66
}
90
- }
67
+ }
0 commit comments