Skip to content
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

_.unzip as the inverse of _.zip #1038

Merged
merged 2 commits into from
Mar 30, 2013
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
Added unzip function (and helper) as inverse of _.zip per ticket #1015
  • Loading branch information
fogus committed Mar 13, 2013
commit 9f471e05f6eb02655e8235d24e80f2259b7f538d
9 changes: 9 additions & 0 deletions test/arrays.js
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,15 @@ $(document).ready(function() {
equal(String(stooges), 'moe,30,true,larry,40,,curly,50,', 'zipped together arrays of different lengths');
});

test('unzip', function() {
var stoogesZipped = [['moe',30],['larry',40],['curly',50]];
var stoogesUnzipped = _.unzip(stoogesZipped);
equal(String(stoogesUnzipped), 'moe,larry,curly,30,40,50', 'unzipped pairs');

var emptyUnzipped = _.unzip([]);
equal(String(emptyUnzipped), ',', 'unzipped empty pairs');
});

test('object', function() {
var result = _.object(['moe', 'larry', 'curly'], [30, 40, 50]);
var shouldBe = {moe: 30, larry: 40, curly: 50};
Expand Down
16 changes: 16 additions & 0 deletions underscore.js
Original file line number Diff line number Diff line change
Expand Up @@ -499,6 +499,22 @@
return results;
};

// Internal helper function for `_.unzip`. Builds arrays out of the
// first and second elements.
function constructPair(pair, rests) {
return [[_.first(pair)].concat(_.first(rests)),
[_.first(_.rest(pair))].concat(_.first(_.rest(rests)))];
}

// The inverse operation to `_.zip`. That is, takes an array of pairs and
// returns an array of the paired elements split into two left and right
// element arrays. For example, `_.unzip` given `[['a',1],['b',2],['c',3]]`
// returns the array [['a','b','c'],[1,2,3]].
_.unzip = function(pairs) {
if (_.isEmpty(pairs)) return [[],[]];
return constructPair(_.first(pairs), _.unzip(_.rest(pairs)));
};

// Converts lists into objects. Pass either a single array of `[key, value]`
// pairs, or two parallel arrays of the same length -- one of keys, and one of
// the corresponding values.
Expand Down