group.js 614 B

12345678910111213141516171819202122232425262728
  1. // Inspired by Underscore's groupBy:
  2. // http://documentcloud.github.com/underscore/#groupBy
  3. "use strict";
  4. var callable = require("../../object/valid-callable")
  5. , value = require("../../object/valid-value")
  6. , forEach = Array.prototype.forEach
  7. , apply = Function.prototype.apply;
  8. module.exports = function (cb /*, thisArg*/) {
  9. var result;
  10. value(this);
  11. callable(cb);
  12. result = Object.create(null);
  13. forEach.call(
  14. this,
  15. function (item) {
  16. var key = apply.call(cb, this, arguments);
  17. if (!result[key]) result[key] = [];
  18. result[key].push(item);
  19. },
  20. arguments[1]
  21. );
  22. return result;
  23. };