@@ -75,5 +75,27 @@ describe('diff/array', function() {
7575 { count : 1 , value : [ d ] , removed : undefined , added : true }
7676 ] ) ;
7777 } ) ;
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+ } ) ;
78100 } ) ;
79101} ) ;
0 commit comments