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

feat(blog): group sidebar items by year (themeConfig.blog.sidebar.groupByYear) #10252

Merged
merged 12 commits into from
Jun 28, 2024
Prev Previous commit
Next Next commit
test groupBy
  • Loading branch information
slorber committed Jun 28, 2024
commit c660c6f51e93567f5254edc937f12f1e802ee76f
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ function groupBlogSidebarItemsByYear(
// Objects with string/number keys are automatically sorted asc...
// Even if keys are strings like "2024"
// We want descending order for years
// Alternative: using Map.groupBy (not affected by this "reordering")
entries.reverse();
return entries;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/

import {uniq, duplicates} from '../jsUtils';
import {uniq, duplicates, groupBy} from '../jsUtils';

describe('duplicates', () => {
it('gets duplicate values', () => {
Expand Down Expand Up @@ -51,3 +51,55 @@ describe('uniq', () => {
).toEqual([obj1, obj2, array1, array3, array2, obj3]);
});
});

describe('groupBy', () => {
type User = {name: string; age: number; type: 'a' | 'b' | 'c'};

const user1: User = {name: 'Seb', age: 42, type: 'c'};
const user2: User = {name: 'Robert', age: 42, type: 'b'};
const user3: User = {name: 'Seb', age: 32, type: 'c'};

const users = [user1, user2, user3];

it('group by name', () => {
const groups = groupBy(users, (u) => u.name);

expect(Object.keys(groups)).toEqual(['Seb', 'Robert']);
expect(groups).toEqual({
Seb: [user1, user3],
Robert: [user2],
});
});

it('group by age', () => {
const groups = groupBy(users, (u) => u.age);

// Surprising keys order due to JS behavior
// see https://x.com/sebastienlorber/status/1806371668614369486
expect(Object.keys(groups)).toEqual(['32', '42']);
expect(groups).toEqual({
'32': [user3],
'42': [user1, user2],
});
});

it('group by type', () => {
const groups = groupBy(users, (u) => u.type);

expect(Object.keys(groups)).toEqual(['c', 'b']);
expect(groups).toEqual({
c: [user1, user3],
b: [user2],
});
});

it('group by name even duplicates', () => {
const groups = groupBy([user1, user2, user3, user1, user3], (u) => u.name);

expect(Object.keys(groups)).toEqual(['Seb', 'Robert']);
expect(groups).toEqual({
Seb: [user1, user3, user1, user3],
Robert: [user2],
});
});
});