实现说明
实际承担运算责任的是函数体 groupByPropertyKey,其余都是接线。
这个示例中仅有的重复出现在 for (const item of items) 里。
使用要点
- 运行之前不需要往项目里加任何东西。
- 直接运行文件,输出会带上标签,比如
200 paths:、labels:——输出的每一行都能指回产生它的那次调用。
常见问题
在一个没有任何依赖声明的空项目里能跑吗?
可以——空项目原样能跑,因为什么都不用声明。 文件在加载时定义 groupByPropertyKey。
核心语句
const byStatus = groupByPropertyKey(routes, (r) => r.status);
const buckets = new Map<K, T[]>();
代码示例
// PropertyKey is the built-in union: string | number | symbol
function groupByPropertyKey<T, K extends PropertyKey>(
items: readonly T[],
pickKey: (item: T) => K,
): Map<K, T[]> {
const buckets = new Map<K, T[]>();
for (const item of items) {
const key = pickKey(item);
const list = buckets.get(key);
if (list) {
list.push(item);
} else {
buckets.set(key, [item]);
}
}
return buckets;
}
const internalTag = Symbol('internal');
const routes = [
{ status: 200 as const, path: '/health' },
{ status: 404 as const, path: '/missing' },
{ status: 200 as const, path: '/ready' },
];
const byStatus = groupByPropertyKey(routes, (r) => r.status);
const labels: Record<PropertyKey, string> = {
200: 'ok',
default: 'fallback',
[internalTag]: 'hidden',
};
console.log('200 paths:', byStatus.get(200)?.map((r) => r.path).join(','));
console.log('labels:', labels[200], labels.default, labels[internalTag]);