Skip to content

Instantly share code, notes, and snippets.

@henrahmagix
Last active December 20, 2015 06:49
Show Gist options
  • Select an option

  • Save henrahmagix/6088580 to your computer and use it in GitHub Desktop.

Select an option

Save henrahmagix/6088580 to your computer and use it in GitHub Desktop.
Difference in map between underscore/lodash and jQuery/Zepto.
// Difference in map between underscore/lodash and jQuery/Zepto.
//
// $ allows filtering at the same time; _ does not.
//
// In your client-side JavaScript apps that use _ and $, this can come as a
// surprise since the assumption is that all your map, each, filter, etc. needs
// are fulfilled by _, and you'd be right to use them for speed since they
// alias native methods where available. However, sometimes $ can be useful,
// and this is one such case where that's true.
//
// The battle is between speed and verbosity, where $ potentially wins the
// former (half the loop iterations) but the last line using _ wins the latter.
var numbers = [1,2,3,4];
var doubleEven = function (n) {
if (n % 2) return;
return n * 2;
};
_.map(numbers, doubleEven);
// -> [undefined, 4, undefined, 8]
$.map(numbers, doubleEven);
// -> [4, 8]
// Desired outcome using _
var oddFilter = function (n) {
return ! (n % 2);
};
_.chain(numbers).filter(oddFilter).map(doubleEven).value();
// -> [4, 8]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment