8
0
Просмотр исходного кода

Added getters for the first and last item from the coooection.

Oskar Wróbel 8 лет назад
Родитель
Сommit
a827d4b50f

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

@@ -98,6 +98,24 @@ export default class Collection {
 		return this._items.length;
 	}
 
+	/**
+	 * Returns the first item from the collection or null when collection is empty.
+	 *
+	 * @returns {Object|null} The first item or `null` if collection is empty.
+	 */
+	get first() {
+		return this._items[ 0 ] || null;
+	}
+
+	/**
+	 * Returns the last item from the collection or null when collection is empty.
+	 *
+	 * @returns {Object|null} The last item or `null` if collection is empty.
+	 */
+	get last() {
+		return this._items[ this.length - 1 ] || null;
+	}
+
 	/**
 	 * Adds an item into the collection.
 	 *
@@ -162,7 +180,7 @@ export default class Collection {
 	 * Gets item by its id or index.
 	 *
 	 * @param {String|Number} idOrIndex The item id or index in the collection.
-	 * @returns {Object} The requested item or `null` if such item does not exist.
+	 * @returns {Object|null} The requested item or `null` if such item does not exist.
 	 */
 	get( idOrIndex ) {
 		let item;

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

@@ -40,6 +40,48 @@ describe( 'Collection', () => {
 		} );
 	} );
 
+	describe( 'length', () => {
+		it( 'should return collection length', () => {
+			expect( collection.length ).to.equal( 0 );
+
+			collection.add( { foo: 'bar' } );
+
+			expect( collection.length ).to.equal( 1 );
+		} );
+	} );
+
+	describe( 'first', () => {
+		it( 'should return the first item from the collection', () => {
+			const item1 = { foo: 'bar' };
+			const item2 = { bar: 'biz' };
+
+			collection.add( item1 );
+			collection.add( item2 );
+
+			expect( collection.first ).to.equal( item1 );
+		} );
+
+		it( 'should return null when collection is empty', () => {
+			expect( collection.first ).to.null;
+		} );
+	} );
+
+	describe( 'last', () => {
+		it( 'should return the last item from the collection', () => {
+			const item1 = { foo: 'bar' };
+			const item2 = { bar: 'biz' };
+
+			collection.add( item1 );
+			collection.add( item2 );
+
+			expect( collection.last ).to.equal( item2 );
+		} );
+
+		it( 'should return null when collection is empty', () => {
+			expect( collection.last ).to.null;
+		} );
+	} );
+
 	describe( 'add()', () => {
 		it( 'should be chainable', () => {
 			expect( collection.add( {} ) ).to.equal( collection );