
本文详细介绍了如何使用 TypeScript 创建一个通用的、类型安全的 groupBySum 函数,该函数可以根据任意数量的对象键对对象数组进行分组,并对第二组任意数量的键的值进行求和。该函数避免了硬编码键名,并充分利用 TypeScript 的类型系统,保证了代码的健壮性和可维护性。
以下是一个使用 TypeScript 实现的 groupBySum 函数,它满足了所有期望的要求:
/**
* 对对象数组中的对象值进行求和,并按任意对象键进行分组。
*
* @remarks
* 此方法接受并返回一个对象数组。
* 生成的对象数组包含原始数组中对象键的子集。
*
* @param arr - 要分组和求和的对象数组。
* @param groupByKeys - 用于分组的键的数组。
* @param sumKeys - 用于求和的键的数组。这些键必须引用数值。
* @returns 一个对象数组,按 groupByKeys 分组,并对 sumKeys 中的键的值进行求和。
*/
const groupBySum = <T, K extends keyof T, S extends keyof T>(
arr: T[],
groupByKeys: K[],
sumKeys: S[]
): Pick<T, K | S>[] => {
return [
...arr
.reduce((accu, curr) => {
const keyArr = groupByKeys.map((key) => curr[key]);
const key = keyArr.join("-");
const groupedSum =
accu.get(key) ||
Object.assign(
{},
Object.fromEntries(groupByKeys.map((key) => [key, curr[key]])),
Object.fromEntries(sumKeys.map((key) => [key, key in curr ? curr[key] : 0]))
);
for (let key of sumKeys) {
groupedSum[key] = (groupedSum[key] || 0) + (curr[key] || 0);
}
return accu.set(key, groupedSum);
}, new Map())
.values(),
];
};此函数接受三个参数:
该函数返回一个新的对象数组,其中包含按 groupByKeys 分组的原始数组中的对象,并且 sumKeys 中的值已被求和。
以下是一些使用 JavaScript 等效代码的示例,基于以下 arr 数组:
const arr = [
{ shape: "square", color: "red", available: 1, ordered: 1 },
{ shape: "square", color: "red", available: 2, ordered: 1 },
{ shape: "circle", color: "blue", available: 0, ordered: 3 },
{ shape: "square", color: "blue", available: 4, ordered: 4 },
];
const groupBySum = (arr, groupByKeys, sumKeys) => {
return [
...arr
.reduce((accu, curr) => {
const keyArr = groupByKeys.map((key) => curr[key]);
const key = keyArr.join("-");
const groupedSum =
accu.get(key) ||
Object.assign(
{},
Object.fromEntries(groupByKeys.map((key) => [key, curr[key]])),
Object.fromEntries(sumKeys.map((key) => [key, 0]))
);
for (let key of sumKeys) {
groupedSum[key] += curr[key];
}
return accu.set(key, groupedSum);
}, new Map())
.values(),
];
};
console.log('groupBySum(arr, ["shape"], ["available"])')
console.log(groupBySum(arr, ["shape"], ["available"]))
console.log('\n\ngroupBySum(arr, ["color"], ["ordered"])')
console.log(groupBySum(arr, ["color"], ["ordered"]))
console.log('\n\ngroupBySum(arr, ["shape", "color"], ["available", "ordered"])')
console.log(groupBySum(arr, ["shape", "color"], ["available", "ordered"]))这些示例展示了如何使用 groupBySum 函数按不同的键进行分组,并对不同的值进行求和。
TypeScript 实现是类型安全的。例如,如果我们尝试传递一个无效的键,编译器会报错:
groupBySum(arr, ["blah"], ["ordered"]);
错误信息如下:
Type '"blah"' is not assignable to type '"shape" | "ordered" | "color" | "available"'.ts(2322)
返回的对象也是类型安全的。例如,ans 的类型在以下代码中:
const ans = groupBySum(arr, ["shape"], ["ordered"])
是:
Array<{ shape: string; ordered: number }>;通过使用 TypeScript 的泛型和类型推断,我们可以创建一个通用的、类型安全的 groupBySum 函数,它可以根据任意数量的对象键对对象数组进行分组,并对第二组任意数量的键的值进行求和。这个函数不仅可以提高代码的可读性和可维护性,还可以避免运行时错误。
以上就是使用 TypeScript 实现类型安全的动态分组求和的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号