forked from lodash/lodash
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgroupBy.js
More file actions
68 lines (54 loc) · 2.45 KB
/
groupBy.js
File metadata and controls
68 lines (54 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import assert from 'assert';
import lodashStable from 'lodash';
import { LARGE_ARRAY_SIZE } from './utils.js';
import groupBy from '../groupBy.js';
describe('groupBy', function() {
var array = [6.1, 4.2, 6.3];
it('should transform keys by `iteratee`', function() {
var actual = groupBy(array, Math.floor);
assert.deepStrictEqual(actual, { '4': [4.2], '6': [6.1, 6.3] });
});
it('should use `_.identity` when `iteratee` is nullish', function() {
var array = [6, 4, 6],
values = [, null, undefined],
expected = lodashStable.map(values, lodashStable.constant({ '4': [4], '6': [6, 6] }));
var actual = lodashStable.map(values, function(value, index) {
return index ? groupBy(array, value) : groupBy(array);
});
assert.deepStrictEqual(actual, expected);
});
it('should work with `_.property` shorthands', function() {
var actual = groupBy(['one', 'two', 'three'], 'length');
assert.deepStrictEqual(actual, { '3': ['one', 'two'], '5': ['three'] });
});
it('should only add values to own, not inherited, properties', function() {
var actual = groupBy(array, function(n) {
return Math.floor(n) > 4 ? 'hasOwnProperty' : 'constructor';
});
assert.deepStrictEqual(actual.constructor, [4.2]);
assert.deepStrictEqual(actual.hasOwnProperty, [6.1, 6.3]);
});
it('should work with a number for `iteratee`', function() {
var array = [
[1, 'a'],
[2, 'a'],
[2, 'b']
];
assert.deepStrictEqual(groupBy(array, 0), { '1': [[1, 'a']], '2': [[2, 'a'], [2, 'b']] });
assert.deepStrictEqual(groupBy(array, 1), { 'a': [[1, 'a'], [2, 'a']], 'b': [[2, 'b']] });
});
it('should work with an object for `collection`', function() {
var actual = groupBy({ 'a': 6.1, 'b': 4.2, 'c': 6.3 }, Math.floor);
assert.deepStrictEqual(actual, { '4': [4.2], '6': [6.1, 6.3] });
});
it('should work in a lazy sequence', function() {
var array = lodashStable.range(LARGE_ARRAY_SIZE).concat(
lodashStable.range(Math.floor(LARGE_ARRAY_SIZE / 2), LARGE_ARRAY_SIZE),
lodashStable.range(Math.floor(LARGE_ARRAY_SIZE / 1.5), LARGE_ARRAY_SIZE)
);
var iteratee = function(value) { value.push(value[0]); return value; },
predicate = function(value) { return isEven(value[0]); },
actual = _(array).groupBy().map(iteratee).filter(predicate).take().value();
assert.deepEqual(actual, _.take(_.filter(lodashStable.map(groupBy(array), iteratee), predicate)));
});
});