Skip to content
This repository was archived by the owner on Jun 26, 2020. It is now read-only.

Commit

Permalink
Merge pull request #267 from ckeditor/t/266
Browse files Browse the repository at this point in the history
Feature: introduce `Collection.has()` method. Closes #266.
  • Loading branch information
jodator authored Jan 3, 2019
2 parents 4ad23b1 + a3eebbe commit 312d55e
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 5 deletions.
27 changes: 22 additions & 5 deletions src/collection.js
Original file line number Diff line number Diff line change
Expand Up @@ -209,20 +209,37 @@ export default class Collection {
return item || null;
}

/**
* Returns a boolean indicating whether the collection contains an item.
*
* @param {Object|String} itemOrId The item or its id in the collection.
* @returns {Boolean} `true` if the collection contains the item, `false` otherwise.
*/
has( itemOrId ) {
if ( typeof itemOrId == 'string' ) {
return this._itemMap.has( itemOrId );
} else { // Object
const idProperty = this._idProperty;
const id = itemOrId[ idProperty ];

return this._itemMap.has( id );
}
}

/**
* 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.
* @param {Object|String} itemOrId The item or its id in the collection.
* @returns {Number} Index of given item.
*/
getIndex( idOrItem ) {
getIndex( itemOrId ) {
let item;

if ( typeof idOrItem == 'string' ) {
item = this._itemMap.get( idOrItem );
if ( typeof itemOrId == 'string' ) {
item = this._itemMap.get( itemOrId );
} else {
item = idOrItem;
item = itemOrId;
}

return this._items.indexOf( item );
Expand Down
28 changes: 28 additions & 0 deletions tests/collection.js
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,34 @@ describe( 'Collection', () => {
} );
} );

describe( 'has()', () => {
it( 'should return true if collection contains item with given id', () => {
collection.add( getItem( 'foo' ) );

expect( collection.has( 'foo' ) ).to.equal( true );
} );

it( 'should return false if collection does not contain item with given id', () => {
collection.add( getItem( 'foo' ) );

expect( collection.has( 'bar' ) ).to.equal( false );
} );

it( 'should return true if collection contains item', () => {
const item = getItem( 'foo' );

collection.add( item );

expect( collection.has( item ) ).to.equal( true );
} );

it( 'should return false if collection does not contains item', () => {
collection.add( getItem( 'foo' ) );

expect( collection.has( getItem( 'bar' ) ) ).to.equal( false );
} );
} );

describe( 'getIndex()', () => {
it( 'should return index of given item', () => {
const item1 = { foo: 'bar' };
Expand Down

0 comments on commit 312d55e

Please sign in to comment.