8
0
Piotr Jasiun 7 лет назад
Родитель
Сommit
784c066076

+ 23 - 0
packages/ckeditor5-utils/src/collection.js

@@ -209,6 +209,29 @@ export default class Collection {
 		return item || null;
 	}
 
+	/**
+	 * Returns a boolean indicating whether the collection contains an item with the specified id or index.
+	 *
+	 * @param {String|Number} idOrIndex The item id or index in the collection.
+	 * @returns {Boolean} `true` if the collection contains the item, `false` otherwise.
+	 */
+	has( idOrIndex ) {
+		let item;
+
+		if ( typeof idOrIndex == 'string' ) {
+			return this._itemMap.has( idOrIndex );
+		} else if ( typeof idOrIndex == 'number' ) {
+			return !!this._items[ idOrIndex ];
+		}
+
+		/**
+		 * Index or id must be given.
+		 *
+		 * @error collection-has-invalid-arg
+		 */
+		throw new CKEditorError( 'collection-has-invalid-arg: Index or id must be given.' );
+	}
+
 	/**
 	 * Gets index of item in the collection.
 	 * When item is not defined in the collection then index will be equal -1.

+ 36 - 0
packages/ckeditor5-utils/tests/collection.js

@@ -321,6 +321,42 @@ describe( 'Collection', () => {
 		} );
 	} );
 
+	describe( 'has()', () => {
+		it( 'should return true if collection contains item', () => {
+			collection.add( getItem( 'foo' ) );
+
+			expect( collection.has( 'foo' ) ).to.equal( true );
+		} );
+
+		it( 'should return false if collection does not contain item', () => {
+			collection.add( getItem( 'foo' ) );
+
+			expect( collection.has( 'bar' ) ).to.equal( false );
+		} );
+
+		it( 'should return true if collection contains item on index', () => {
+			collection.add( getItem( 'foo' ) );
+			collection.add( getItem( 'bar' ) );
+
+			expect( collection.has( 0 ) ).to.equal( true );
+			expect( collection.has( 1 ) ).to.equal( true );
+		} );
+
+		it( 'should return false if collection does not contain item on index', () => {
+			collection.add( getItem( 'foo' ) );
+			collection.add( getItem( 'bar' ) );
+
+			expect( collection.has( -1 ) ).to.equal( false );
+			expect( collection.has( 2 ) ).to.equal( false );
+		} );
+
+		it( 'should throw if neither string or number given', () => {
+			expect( () => {
+				collection.has( true );
+			} ).to.throw( CKEditorError, /^collection-has-invalid-arg/ );
+		} );
+	} );
+
 	describe( 'getIndex()', () => {
 		it( 'should return index of given item', () => {
 			const item1 = { foo: 'bar' };