added oneToMany option to _.invert()

This commit is contained in:
Scott Shepherd
2013-12-05 09:12:38 -05:00
parent c2972fcaa0
commit efb1a2c8e0
2 changed files with 19 additions and 3 deletions

View File

@@ -2540,21 +2540,31 @@
* @memberOf _ * @memberOf _
* @category Objects * @category Objects
* @param {Object} object The object to invert. * @param {Object} object The object to invert.
* @param {boolean} oneToMany allow multiple values for each key in the inverted result
* @returns {Object} Returns the created inverted object. * @returns {Object} Returns the created inverted object.
* @example * @example
* *
* _.invert({ 'first': 'fred', 'second': 'barney' }); * _.invert({ 'first': 'fred', 'second': 'barney' });
* // => { 'fred': 'first', 'barney': 'second' } * // => { 'fred': 'first', 'barney': 'second' }
*
* _.invert({ 'first': 'fred', 'second': 'barney', 'third': 'fred' }, true);
* // => { 'fred': ['first', 'third'], 'barney': ['second'] }
*/ */
function invert(object) { function invert(object, oneToMany) {
var index = -1, var index = -1,
props = keys(object), props = keys(object),
length = props.length, length = props.length,
result = {}; result = {};
while (++index < length) { while (++index < length) {
var key = props[index]; var key = props[index],
result[object[key]] = key; value = object[key];
if (oneToMany) {
result[value] = result[value] || [];
result[value].push(key);
} else {
result[value] = key;
}
} }
return result; return result;
} }

View File

@@ -3306,6 +3306,12 @@
var object = { '0': 'a', '1': 'b', 'length': 2 }; var object = { '0': 'a', '1': 'b', 'length': 2 };
deepEqual(_.invert(object), { 'a': '0', 'b': '1', '2': 'length' }); deepEqual(_.invert(object), { 'a': '0', 'b': '1', '2': 'length' });
}); });
test('should accept the one-to-many flag', 1, function() {
var object = { '0': 'a', '1': 'b', '2': 'a' };
deepEqual(_.invert(object, true), { 'a': ['0', '2'], 'b': ['1'] });
});
}()); }());
/*--------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------*/