Explorar el Código

Added tests and docs to the edge cases in the 'nth' function.

Maciej Bukowski hace 8 años
padre
commit
3eedcdcea7
Se han modificado 2 ficheros con 26 adiciones y 7 borrados
  1. 4 2
      packages/ckeditor5-utils/src/nth.js
  2. 22 5
      packages/ckeditor5-utils/tests/nth.js

+ 4 - 2
packages/ckeditor5-utils/src/nth.js

@@ -8,14 +8,16 @@
  */
 
 /**
- * Returns `nth` (starts from `0` of course) item of an `iterable`.
+ * Returns `nth` (starts from `0` of course) item of the given `iterable`.
+ * Consumes all items of the generator.
+ * Consumes all items up to the index of the iterator, including the returned item.
  *
  * @param {Number} index
  * @param {Iterable.<*>} iterable
  * @returns {*}
  */
 export default function nth( index, iterable ) {
-	for ( let item of iterable ) {
+	for ( const item of iterable ) {
 		if ( index === 0 ) {
 			return item;
 		}

+ 22 - 5
packages/ckeditor5-utils/tests/nth.js

@@ -8,26 +8,43 @@ import nth from '../src/nth';
 describe( 'utils', () => {
 	describe( 'nth', () => {
 		it( 'should return 0th item', () => {
-			expect( nth( 0, getIterator() ) ).to.equal( 11 );
+			expect( nth( 0, getGenerator() ) ).to.equal( 11 );
 		} );
 
 		it( 'should return the last item', () => {
-			expect( nth( 2, getIterator() ) ).to.equal( 33 );
+			expect( nth( 2, getGenerator() ) ).to.equal( 33 );
 		} );
 
 		it( 'should return null if out of range (bottom)', () => {
-			expect( nth( -1, getIterator() ) ).to.be.null;
+			expect( nth( -1, getGenerator() ) ).to.be.null;
 		} );
 
 		it( 'should return null if out of range (top)', () => {
-			expect( nth( 3, getIterator() ) ).to.be.null;
+			expect( nth( 3, getGenerator() ) ).to.be.null;
 		} );
 
 		it( 'should return null if iterator is empty', () => {
 			expect( nth( 0, [] ) ).to.be.null;
 		} );
 
-		function *getIterator() {
+		it( 'should consume the given generator', () => {
+			const generator = getGenerator();
+
+			nth( 0, generator );
+
+			expect( generator.next().done ).to.equal( true );
+		} );
+
+		it( 'should stop inside the given iterator', () => {
+			const collection = [ 11, 22, 33 ];
+			const iterator = collection[ Symbol.iterator ]();
+
+			nth( 0, iterator );
+
+			expect( iterator.next().value ).to.equal( 22 );
+		} );
+
+		function *getGenerator() {
 			yield 11;
 			yield 22;
 			yield 33;