8
0
Pārlūkot izejas kodu

Merge pull request #138 from ckeditor/t/137

Internal: Added tests and docs for the edge cases in the `nth()` function. Closes #137.
Piotrek Koszuliński 8 gadi atpakaļ
vecāks
revīzija
4439792069

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

@@ -8,14 +8,19 @@
  */
 
 /**
- * Returns `nth` (starts from `0` of course) item of an `iterable`.
+ * Returns `nth` (starts from `0` of course) item of the given `iterable`.
+ *
+ * If the iterable is a generator, then it consumes **all its items**.
+ * If it's a normal iterator, then it consumes **all items up to the given index**.
+ * Refer to the [Iterators and Generators](https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Iterators_and_Generators)
+ * guide to learn differences between these interfaces.
  *
  * @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;