瀏覽代碼

Added getIndex method to Collection class.

Oskar Wróbel 9 年之前
父節點
當前提交
6b7c5ed874
共有 2 個文件被更改,包括 55 次插入0 次删除
  1. 19 0
      packages/ckeditor5-utils/src/collection.js
  2. 36 0
      packages/ckeditor5-utils/tests/collection.js

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

@@ -153,6 +153,25 @@ export default class Collection {
 	}
 
 	/**
+	 * Gets index of item in the collection.
+	 * When item is not defined in the collection then index will be equal -1.
+	 *
+	 * @param {String|Object} idOrItem The item or its id in the collection.
+	 * @returns {Number} Index of given item.
+	 */
+	getIndex( idOrItem ) {
+		let item;
+
+		if ( typeof idOrItem == 'string' ) {
+			item = this._itemMap.get( idOrItem );
+		} else {
+			item = idOrItem;
+		}
+
+		return this._items.indexOf( item );
+	}
+
+	/**
 	 * Removes an item from the collection.
 	 *
 	 * @param {Object|Number|String} subject The item to remove, its id or index in the collection.

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

@@ -281,6 +281,42 @@ describe( 'Collection', () => {
 		} );
 	} );
 
+	describe( 'getIndex', () => {
+		it( 'should return index of given item', () => {
+			const item1 = { foo: 'bar' };
+			const item2 = { bar: 'biz' };
+			const item3 = { foo: 'biz' };
+
+			collection.add( item1 );
+			collection.add( item2 );
+			collection.add( item3 );
+
+			expect( collection.getIndex( item1 ) ).to.equal( 0 );
+			expect( collection.getIndex( item2 ) ).to.equal( 1 );
+			expect( collection.getIndex( item3 ) ).to.equal( 2 );
+		} );
+
+		it( 'should return index of item with given id', () => {
+			collection.add( { id: 'id1' } );
+			collection.add( { id: 'id2' } );
+			collection.add( { id: 'id3' } );
+
+			expect( collection.getIndex( 'id1' ) ).to.equal( 0 );
+			expect( collection.getIndex( 'id2' ) ).to.equal( 1 );
+			expect( collection.getIndex( 'id3' ) ).to.equal( 2 );
+		} );
+
+		it( 'should return index equal to -1 when given item is not defined in the collection', () => {
+			const item1 = { foo: 'bar' };
+
+			expect( collection.getIndex( item1 ) ).to.equal( -1 );
+		} );
+
+		it( 'should return index equal to -1 when item of given id is not defined in the collection', () => {
+			expect( collection.getIndex( 'id1' ) ).to.equal( -1 );
+		} );
+	} );
+
 	describe( 'remove', () => {
 		it( 'should remove the model by index', () => {
 			collection.add( getItem( 'bom' ) );