Skip to content

Add support for maps in _.pairs method ...Closes #2517 #2523

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions test/objects.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,12 @@
QUnit.test('pairs', function(assert) {
assert.deepEqual(_.pairs({one: 1, two: 2}), [['one', 1], ['two', 2]], 'can convert an object into pairs');
assert.deepEqual(_.pairs({one: 1, two: 2, length: 3}), [['one', 1], ['two', 2], ['length', 3]], '... even when one of them is "length"');
if (typeof Map === 'function') {
var mapObj = new Map();
mapObj.set('one', 1);
mapObj.set('two', 2);
assert.deepEqual(_.pairs(mapObj), [['one', 1], ['two', 2]], '... or when object is a Map');
}
});

QUnit.test('invert', function(assert) {
Expand Down
10 changes: 10 additions & 0 deletions underscore.js
Original file line number Diff line number Diff line change
Expand Up @@ -435,6 +435,15 @@
if (_.has(result, key)) result[key]++; else result[key] = 1;
});

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For this PR I just made the change in _.pairs, but the helper function allows quick checks in other underscore functions as well, as @jdalton mentioned (i.e. _.toArray).

var mapToArray = function(map) {
var index = -1;
var result = Array(map.size);
map.forEach(function(value, key) {
result[++index] = [key, value];
});
return result;
};

var reStrSymbol = /[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g;
// Safely create a real, live array from anything iterable.
_.toArray = function(obj) {
Expand Down Expand Up @@ -1009,6 +1018,7 @@

// Convert an object into a list of `[key, value]` pairs.
_.pairs = function(obj) {
if (_.isMap(obj)) return mapToArray(obj);
var keys = _.keys(obj);
var length = keys.length;
var pairs = Array(length);
Expand Down