@@ -75,5 +75,27 @@ describe('diff/array', function() {
75
75
{ count : 1 , value : [ d ] , removed : undefined , added : true }
76
76
] ) ;
77
77
} ) ;
78
+ it ( 'Should terminate early if execution time exceeds `timeout` ms' , function ( ) {
79
+ // To test this, we also pass a comparator that hot sleeps as a way to
80
+ // artificially slow down execution so we reach the timeout.
81
+ function comparator ( left , right ) {
82
+ const start = Date . now ( ) ;
83
+ // Hot-sleep for 10ms
84
+ while ( Date . now ( ) < start + 10 ) {
85
+ // Do nothing
86
+ }
87
+ return left === right ;
88
+ }
89
+
90
+ // It will require 14 comparisons (140ms) to diff these arrays:
91
+ const arr1 = [ 'a' , 'b' , 'c' , 'd' , 'e' , 'f' , 'g' ] ;
92
+ const arr2 = [ 'a' , 'b' , 'c' , 'd' , 'x' , 'y' , 'z' ] ;
93
+
94
+ // So with a timeout of 50ms, we are guaranteed failure:
95
+ expect ( diffArrays ( arr1 , arr2 , { comparator, timeout : 50 } ) ) . to . be . undefined ;
96
+
97
+ // But with a longer timeout, we expect success:
98
+ expect ( diffArrays ( arr1 , arr2 , { comparator, timeout : 1000 } ) ) . not . to . be . undefined ;
99
+ } ) ;
78
100
} ) ;
79
101
} ) ;
0 commit comments