8
0
فهرست منبع

Feature: Added 'first' function. Closes #130.

Piotr Jasiun 8 سال پیش
والد
کامیت
47c963c085
2فایلهای تغییر یافته به همراه57 افزوده شده و 0 حذف شده
  1. 24 0
      packages/ckeditor5-utils/src/first.js
  2. 33 0
      packages/ckeditor5-utils/tests/first.js

+ 24 - 0
packages/ckeditor5-utils/src/first.js

@@ -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 - 0
packages/ckeditor5-utils/tests/first.js

@@ -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 );
+		} );
+	} );
+} );