浏览代码

Introduced Utils.toMap.

Piotr Jasiun 10 年之前
父节点
当前提交
9e362232ec
共有 2 个文件被更改,包括 52 次插入1 次删除
  1. 21 1
      packages/ckeditor5-utils/src/utils.js
  2. 31 0
      packages/ckeditor5-utils/tests/utils.js

+ 21 - 1
packages/ckeditor5-utils/src/utils.js

@@ -5,6 +5,8 @@
 
 'use strict';
 
+import langUtils from './lib/lodash/lang.js';
+
 /**
  * An index at which arrays differ. If arrays are same at all indexes, it represents how arrays are related.
  * In this case, possible values are: 'SAME', 'PREFIX' or 'EXTENSION'.
@@ -92,7 +94,7 @@ const utils = {
 	},
 
 	/**
-	 * Transform object to map.
+	 * Transforms object to map.
 	 *
 	 *		const map = utils.objectToMap( { 'foo': 1, 'bar': 2 } );
 	 *		map.get( 'foo' ); // 1
@@ -111,6 +113,24 @@ const utils = {
 	},
 
 	/**
+	 * Transforms object or iterable to map. Iterable needs to be in the format acceptable by the `Map` constructor.
+	 *
+	 *		map = utils.toMap( { 'foo': 1, 'bar': 2 } );
+	 *		map = utils.toMap( [ [ 'foo', 1 ], [ 'bar', 2 ] ] );
+	 *		map = utils.toMap( anotherMap );
+	 *
+	 * @param {Object|Iterable} data Object or iterable to transform.
+	 * @returns {Map} Map created from data.
+	 */
+	toMap( data ) {
+		if ( langUtils.isPlainObject( data ) ) {
+			return utils.objectToMap( data );
+		} else {
+			return new Map( data );
+		}
+	},
+
+	/**
 	 * Checks whether given {Map}s are equal, that is has same size and same key-value pairs.
 	 *
 	 * @returns {Boolean} `true` if given maps are equal, `false` otherwise.

+ 31 - 0
packages/ckeditor5-utils/tests/utils.js

@@ -6,6 +6,9 @@
 'use strict';
 
 import utils from '/ckeditor5/core/utils.js';
+import coreTestUtils from '/tests/core/_utils/utils.js';
+
+const getIteratorCount = coreTestUtils.getIteratorCount;
 
 describe( 'utils', () => {
 	describe( 'spy', () => {
@@ -116,6 +119,34 @@ describe( 'utils', () => {
 		} );
 	} );
 
+	describe( 'toMap', () => {
+		it( 'should create map from object', () => {
+			const map = utils.toMap( { foo: 1, bar: 2 } );
+
+			expect( getIteratorCount( map ) ).to.equal( 2 );
+			expect( map.get( 'foo' ) ).to.equal( 1 );
+			expect( map.get( 'bar' ) ).to.equal( 2 );
+		} );
+
+		it( 'should create map from iterator', () => {
+			const map = utils.toMap( [ [ 'foo', 1 ], [ 'bar', 2 ] ] );
+
+			expect( getIteratorCount( map ) ).to.equal( 2 );
+			expect( map.get( 'foo' ) ).to.equal( 1 );
+			expect( map.get( 'bar' ) ).to.equal( 2 );
+		} );
+
+		it( 'should create map from another map', () => {
+			const data = new Map( [ [ 'foo', 1 ], [ 'bar', 2 ] ] );
+
+			const map = utils.toMap( data );
+
+			expect( getIteratorCount( map ) ).to.equal( 2 );
+			expect( map.get( 'foo' ) ).to.equal( 1 );
+			expect( map.get( 'bar' ) ).to.equal( 2 );
+		} );
+	} );
+
 	describe( 'mapsEqual', () => {
 		it( 'should return true if maps have exactly same entries (order of adding does not matter)', () => {
 			let mapA = new Map();