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

Commit

Permalink
Feature: Added 'first' function. Closes #130.
Browse files Browse the repository at this point in the history
  • Loading branch information
Piotr Jasiun committed Mar 16, 2017
2 parents 7a0c463 + 1111f37 commit 8ab07d2
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/first.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/**
* @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md.
*/

/**
* @module utils/first
*/

/**
* Returns first item of the given `iterable`.
*
* @param {Iterable.<*>} iterable
* @returns {*}
*/
export default function first( iterable ) {
const iteratorItem = iterable.next();

if ( iteratorItem.done ) {
return null;
}

return iteratorItem.value;
}
33 changes: 33 additions & 0 deletions tests/first.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/**
* @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md.
*/

import first from '../src/first';

describe( 'utils', () => {
describe( 'first', () => {
it( 'should return first item', () => {
const collection = [ 11, 22 ];
const iterator = collection[ Symbol.iterator ]();

expect( first( iterator ) ).to.equal( 11 );
} );

it( 'should return null if iterator is empty', () => {
const collection = [];
const iterator = collection[ Symbol.iterator ]();

expect( first( iterator ) ).to.be.null;
} );

it( 'should consume the iterating item', () => {
const collection = [ 11, 22 ];
const iterator = collection[ Symbol.iterator ]();

first( iterator );

expect( iterator.next().value ).to.equal( 22 );
} );
} );
} );

0 comments on commit 8ab07d2

Please sign in to comment.