Przeglądaj źródła

Internal: Collection type now supports initializing items with any iterable object.

Marek Lewandowski 6 lat temu
rodzic
commit
7d9e49b218

+ 3 - 2
packages/ckeditor5-utils/src/collection.js

@@ -10,6 +10,7 @@
 import EmitterMixin from './emittermixin';
 import CKEditorError from './ckeditorerror';
 import uid from './uid';
+import isIterable from './isiterable';
 import mix from './mix';
 
 /**
@@ -54,14 +55,14 @@ export default class Collection {
 	 *		nonEmptyCollection.add( { name: 'George' } );
 	 *		console.log( collection.get( 'George' ) ); // -> { name: 'George' }
 	 *
-	 * @param {Array.<Object>|Object} initialItemsOrOptions The initial items of the collection or
+	 * @param {Iterable.<Object>|Object} initialItemsOrOptions The initial items of the collection or
 	 * the options object.
 	 * @param {Object} [options={}] The options object, when the first argument is an array of initial items.
 	 * @param {String} [options.idProperty='id'] The name of the property which is used to identify an item.
 	 * Items that do not have such a property will be assigned one when added to the collection.
 	 */
 	constructor( initialItemsOrOptions = {}, options = {} ) {
-		const hasInitialItems = initialItemsOrOptions instanceof Array;
+		const hasInitialItems = isIterable( initialItemsOrOptions );
 
 		if ( !hasInitialItems ) {
 			options = initialItemsOrOptions;

+ 23 - 9
packages/ckeditor5-utils/tests/collection.js

@@ -25,17 +25,31 @@ describe( 'Collection', () => {
 	} );
 
 	describe( 'constructor()', () => {
-		it( 'allows setting initial collection items', () => {
-			const item1 = getItem( 'foo' );
-			const item2 = getItem( 'bar' );
-			const collection = new Collection( [ item1, item2 ] );
+		describe( 'setting initial collection items', () => {
+			it( 'works using an array', () => {
+				const item1 = getItem( 'foo' );
+				const item2 = getItem( 'bar' );
+				const collection = new Collection( [ item1, item2 ] );
 
-			expect( collection ).to.have.length( 2 );
+				expect( collection ).to.have.length( 2 );
 
-			expect( collection.get( 0 ) ).to.equal( item1 );
-			expect( collection.get( 1 ) ).to.equal( item2 );
-			expect( collection.get( 'foo' ) ).to.equal( item1 );
-			expect( collection.get( 'bar' ) ).to.equal( item2 );
+				expect( collection.get( 0 ) ).to.equal( item1 );
+				expect( collection.get( 1 ) ).to.equal( item2 );
+				expect( collection.get( 'foo' ) ).to.equal( item1 );
+				expect( collection.get( 'bar' ) ).to.equal( item2 );
+			} );
+
+			it( 'works using an iterable', () => {
+				const item1 = getItem( 'foo' );
+				const item2 = getItem( 'bar' );
+				const itemsSet = new Set( [ item1, item2 ] );
+				const collection = new Collection( itemsSet );
+
+				expect( collection ).to.have.length( 2 );
+
+				expect( collection.get( 0 ) ).to.equal( item1 );
+				expect( collection.get( 1 ) ).to.equal( item2 );
+			} );
 		} );
 
 		describe( 'options', () => {