UNPKG

2.18 kBJavaScriptView Raw
1var _ = require('underscore');
2var slice = [].slice;
3var mixins = {};
4
5
6// Underscore methods that we want to implement on the Collection.
7var methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl',
8 'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select',
9 'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke',
10 'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest',
11 'tail', 'drop', 'last', 'without', 'difference', 'indexOf', 'shuffle',
12 'lastIndexOf', 'isEmpty', 'chain', 'sample', 'partition'
13];
14
15// Mix in each Underscore method as a proxy to `Collection#models`.
16_.each(methods, function (method) {
17 if (!_[method]) return;
18 mixins[method] = function () {
19 var args = slice.call(arguments);
20 args.unshift(this.models);
21 return _[method].apply(_, args);
22 };
23});
24
25// Underscore methods that take a property name as an argument.
26var attributeMethods = ['groupBy', 'countBy', 'sortBy', 'indexBy'];
27
28// Use attributes instead of properties.
29_.each(attributeMethods, function (method) {
30 if (!_[method]) return;
31 mixins[method] = function (value, context) {
32 var iterator = _.isFunction(value) ? value : function (model) {
33 return model.get ? model.get(value) : model[value];
34 };
35 return _[method](this.models, iterator, context);
36 };
37});
38
39// Return models with matching attributes. Useful for simple cases of
40// `filter`.
41mixins.where = function (attrs, first) {
42 if (_.isEmpty(attrs)) return first ? void 0 : [];
43 return this[first ? 'find' : 'filter'](function (model) {
44 var value;
45 for (var key in attrs) {
46 value = model.get ? model.get(key) : model[key];
47 if (attrs[key] !== value) return false;
48 }
49 return true;
50 });
51};
52
53// Return the first model with matching attributes. Useful for simple cases
54// of `find`.
55mixins.findWhere = function (attrs) {
56 return this.where(attrs, true);
57};
58
59// Plucks an attribute from each model in the collection.
60mixins.pluck = function (attr) {
61 return _.invoke(this.models, 'get', attr);
62};
63
64module.exports = mixins;