瀏覽代碼

Added utils.mapsEqual, utils.objectToMap.

Szymon Cofalik 10 年之前
父節點
當前提交
b8d39aa0fe
共有 2 個文件被更改,包括 56 次插入0 次删除
  1. 41 0
      packages/ckeditor5-utils/src/utils.js
  2. 15 0
      packages/ckeditor5-utils/tests/utils.js

+ 41 - 0
packages/ckeditor5-utils/src/utils.js

@@ -92,6 +92,47 @@ const utils = {
 	},
 
 	/**
+	 * Transform object to map.
+	 *
+	 *		const map = utils.objectToMap( { 'foo': 1, 'bar': 2 } );
+	 *		map.get( 'foo' ); // 1
+	 *
+	 * @param {Object} obj Object to transform.
+	 * @returns {Map} Map created from object.
+	 */
+	objectToMap( obj ) {
+		const map = new Map();
+
+		for ( let key in obj ) {
+			map.set( key, obj[ key ] );
+		}
+
+		return map;
+	},
+
+	/**
+	 * 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.
+	 */
+	mapsEqual( mapA, mapB ) {
+		if ( mapA.size != mapB.size ) {
+			return false;
+		}
+
+		for ( let attr of mapA.entries() ) {
+			let valA = JSON.stringify( attr[ 1 ] );
+			let valB = JSON.stringify( mapB.get( attr[ 0 ] ) );
+
+			if ( valA !== valB ) {
+				return false;
+			}
+		}
+
+		return true;
+	},
+
+	/**
 	 * Returns `nth` (starts from `0` of course) item of an `iterable`.
 	 *
 	 * @param {Number} index

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

@@ -116,6 +116,21 @@ describe( 'utils', () => {
 		} );
 	} );
 
+	describe( 'mapsEqual', () => {
+		it( 'should return true if maps have exactly same entries (order of adding does not matter)', () => {
+			let mapA = new Map();
+			let mapB = new Map();
+
+			mapA.set( 'foo', 'bar' );
+			mapA.set( 'abc', 'xyz' );
+
+			mapB.set( 'abc', 'xyz' );
+			mapB.set( 'foo', 'bar' );
+
+			expect( utils.mapsEqual( mapA, mapB ) ).to.be.true;
+		} );
+	} );
+
 	describe( 'nth', () => {
 		it( 'should return 0th item', () => {
 			expect( utils.nth( 0, getIterator() ) ).to.equal( 11 );