
本文介绍如何使用 TypeScript 实现一个通用的、类型安全的 groupBySum 函数,该函数可以根据任意数量的对象键对对象数组进行分组,并对另一组任意数量的键的值进行求和。该函数不仅具备通用性,而且利用 TypeScript 的类型系统,提供了编译时的类型检查,确保代码的健壮性和可维护性。
以下是 groupBySum 函数的 TypeScript 实现:
/**
* Sums object value(s) in an array of objects, grouping by arbitrary object keys.
*
* @remarks
* This method takes and returns an array of objects.
* The resulting array of object contains a subset of the object keys in the
* original array.
*
* @param arr - The array of objects to group by and sum.
* @param groupByKeys - An array with the keys to group by.
* @param sumKeys - An array with the keys to sum. The keys must refer
* to numeric values.
* @returns An array of objects, grouped by groupByKeys and with the values
* of keys in sumKeys summed up.
*/
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, 0]))
);
for (let key of sumKeys) {
groupedSum[key] += curr[key];
}
return accu.set(key, groupedSum);
}, new Map())
.values(),
];
};代码解释:
泛型定义: groupBySum 函数使用了三个泛型类型:T 代表输入数组中对象的类型,K 代表用于分组的键的类型,S 代表用于求和的键的类型。K 和 S 都被约束为 keyof T,这意味着它们必须是 T 类型对象中存在的键。
参数:
reduce 方法: 使用 reduce 方法遍历输入数组 arr。reduce 方法的第一个参数是一个累加器函数,它接收两个参数:
生成分组键: 使用 groupByKeys.map((key) => curr[key]) 从当前对象 curr 中提取用于分组的键的值,并将它们连接成一个字符串作为分组键。
创建或更新分组对象:
累加求和: 遍历 sumKeys 数组,将当前对象 curr 中对应键的值累加到分组对象中。
返回结果: 将累加器 accu 中的所有值提取到一个新的数组中,并返回该数组。
类型安全: 函数的返回类型 Pick<T, K | S>[] 确保返回的数组中的对象只包含用于分组的键 K 和用于求和的键 S。
以下是一些使用 groupBySum 函数的示例:
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 },
];
// Group by "shape" and sum "available"
const result1 = groupBySum(arr, ["shape"], ["available"]);
console.log('groupBySum(arr, ["shape"], ["available"])')
console.log(result1);
// Output:
// [
// { shape: "square", available: 7 },
// { shape: "circle", available: 0 }
// ]
// Group by "color" and sum "ordered"
const result2 = groupBySum(arr, ["color"], ["ordered"]);
console.log('\n\ngroupBySum(arr, ["color"], ["ordered"])')
console.log(result2);
// Output:
// [
// { color: "red", ordered: 2 },
// { color: "blue", ordered: 7 }
// ]
// Group by "shape" and "color" and sum "available" and "ordered"
const result3 = groupBySum(arr, ["shape", "color"], ["available", "ordered"]);
console.log('\n\ngroupBySum(arr, ["shape", "color"], ["available", "ordered"])')
console.log(result3);
// Output:
// [
// { shape: "square", color: "red", available: 3, ordered: 2 },
// { shape: "circle", color: "blue", available: 0, ordered: 3 },
// { shape: "square", color: "blue", available: 4, ordered: 4 }
// ]TypeScript 的类型系统可以帮助我们在编译时发现错误。例如,如果我们尝试传递一个无效的键,编译器会报错:
// @ts-expect-error groupBySum(arr, ["blah"], ["ordered"]); // Error: Type '"blah"' is not assignable to type '"shape" | "ordered" | "color" | "available"'.ts(2322)
同样,返回对象的类型也是类型安全的。例如,在以下代码中:
const ans = groupBySum(arr, ["shape"], ["ordered"]);
ans 的类型是 Array<{ shape: string; ordered: number; }>。
groupBySum 函数提供了一种通用且类型安全的方法,可以根据任意数量的对象键对对象数组进行分组,并对另一组任意数量的键的值进行求和。 通过利用 TypeScript 的类型系统,该函数可以在编译时捕获错误,并确保代码的健壮性和可维护性。
以上就是使用 TypeScript 实现类型安全的 Group By 和 Sum 操作的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号