@@ -9,7 +9,11 @@ import diffSequences from '@jest/diff-sequences';
9
9
import { DIFF_DELETE , DIFF_EQUAL , DIFF_INSERT , Diff } from './cleanupSemantic' ;
10
10
11
11
const diffStrings = ( a : string , b : string ) : Array < Diff > => {
12
- const isCommon = ( aIndex : number , bIndex : number ) => a [ aIndex ] === b [ bIndex ] ;
12
+ // Split strings into code points to handle surrogate pairs.
13
+ const aCodepoints = [ ...a ] ;
14
+ const bCodepoints = [ ...b ] ;
15
+ const isCommon = ( aIndex : number , bIndex : number ) =>
16
+ aCodepoints [ aIndex ] === bCodepoints [ bIndex ] ;
13
17
14
18
let aIndex = 0 ;
15
19
let bIndex = 0 ;
@@ -21,25 +25,36 @@ const diffStrings = (a: string, b: string): Array<Diff> => {
21
25
bCommon : number ,
22
26
) => {
23
27
if ( aIndex !== aCommon ) {
24
- diffs . push ( new Diff ( DIFF_DELETE , a . slice ( aIndex , aCommon ) ) ) ;
28
+ diffs . push (
29
+ new Diff ( DIFF_DELETE , aCodepoints . slice ( aIndex , aCommon ) . join ( '' ) ) ,
30
+ ) ;
25
31
}
26
32
if ( bIndex !== bCommon ) {
27
- diffs . push ( new Diff ( DIFF_INSERT , b . slice ( bIndex , bCommon ) ) ) ;
33
+ diffs . push (
34
+ new Diff ( DIFF_INSERT , bCodepoints . slice ( bIndex , bCommon ) . join ( '' ) ) ,
35
+ ) ;
28
36
}
29
37
30
38
aIndex = aCommon + nCommon ; // number of characters compared in a
31
39
bIndex = bCommon + nCommon ; // number of characters compared in b
32
- diffs . push ( new Diff ( DIFF_EQUAL , b . slice ( bCommon , bIndex ) ) ) ;
40
+ diffs . push (
41
+ new Diff ( DIFF_EQUAL , bCodepoints . slice ( bCommon , bIndex ) . join ( '' ) ) ,
42
+ ) ;
33
43
} ;
34
44
35
- diffSequences ( a . length , b . length , isCommon , foundSubsequence ) ;
45
+ diffSequences (
46
+ aCodepoints . length ,
47
+ bCodepoints . length ,
48
+ isCommon ,
49
+ foundSubsequence ,
50
+ ) ;
36
51
37
52
// After the last common subsequence, push remaining change items.
38
- if ( aIndex !== a . length ) {
39
- diffs . push ( new Diff ( DIFF_DELETE , a . slice ( aIndex ) ) ) ;
53
+ if ( aIndex !== aCodepoints . length ) {
54
+ diffs . push ( new Diff ( DIFF_DELETE , aCodepoints . slice ( aIndex ) . join ( '' ) ) ) ;
40
55
}
41
- if ( bIndex !== b . length ) {
42
- diffs . push ( new Diff ( DIFF_INSERT , b . slice ( bIndex ) ) ) ;
56
+ if ( bIndex !== bCodepoints . length ) {
57
+ diffs . push ( new Diff ( DIFF_INSERT , bCodepoints . slice ( bIndex ) . join ( '' ) ) ) ;
43
58
}
44
59
45
60
return diffs ;
0 commit comments