mw.Map: add ability to map over an existing object other than 'window'

I don't love the fact that mw.Map features so prominently in mediawiki.js, but
since it's there to stay it might as well be useful for a wider range of use
cases. This patch makes it possible to pass an existing value-bearing object to
be mapped over to the Map constructor.

The effect is the same as constructing the object and then overriding its
'values' attribute. But doing that feels like you're sneaking around the back
to hack the API. Making it part of the official API makes it OK to do.

Change-Id: Id9f8d9569de8889fc3ffa24a6e7f4afca1aeabee
This commit is contained in:
Ori Livneh 2013-10-28 15:58:02 -07:00
parent 7f51cf22f9
commit 63f8d7b9e5
2 changed files with 7 additions and 5 deletions

View file

@ -74,11 +74,11 @@ var mw = ( function ( $, undefined ) {
* @class mw.Map
*
* @constructor
* @param {boolean} [global=false] Whether to store the values in the global window
* object or a exclusively in the object property 'values'.
* @param {Object|boolean} [values] Value-bearing object to map, or boolean
* true to map over the global object. Defaults to an empty object.
*/
function Map( global ) {
this.values = global === true ? window : {};
function Map( values ) {
this.values = values === true ? window : ( values || {} );
return this;
}

View file

@ -43,7 +43,7 @@
assert.strictEqual( window.mw, window.mediaWiki, 'mw alias to mediaWiki' );
} );
QUnit.test( 'mw.Map', 27, function ( assert ) {
QUnit.test( 'mw.Map', 28, function ( assert ) {
var arry, conf, funky, globalConf, nummy, someValues;
conf = new mw.Map();
@ -102,6 +102,8 @@
'lorem': 'ipsum'
}, 'Map.get returns multiple values correctly as an object' );
assert.deepEqual( conf, new mw.Map( conf.values ), 'new mw.Map maps over existing values-bearing object' );
assert.deepEqual( conf.get( ['foo', 'notExist'] ), {
'foo': 'bar',
'notExist': null