值得一看
双11 12
广告
广告

使用 TypeScript 实现类型安全的 Group By 和 Sum 操作

使用 typescript 实现类型安全的 group by 和 sum 操作

本文介绍如何使用 TypeScript 实现一个通用的、类型安全的 groupBySum 函数,该函数可以根据任意数量的对象键对对象数组进行分组,并对另一组任意数量的键的值进行求和。该函数不仅具备通用性,而且利用 TypeScript 的类型系统,提供了编译时的类型检查,确保代码的健壮性和可维护性。

groupBySum 函数的实现

以下是 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(),
];
};

代码解释:

  1. 泛型定义: groupBySum 函数使用了三个泛型类型:T 代表输入数组中对象的类型,K 代表用于分组的键的类型,S 代表用于求和的键的类型。K 和 S 都被约束为 keyof T,这意味着它们必须是 T 类型对象中存在的键。

  2. 参数:

    • arr: 要进行分组和求和的对象数组。
    • groupByKeys: 一个字符串数组,包含用于分组的键。
    • sumKeys: 一个字符串数组,包含用于求和的键。
  3. reduce 方法: 使用 reduce 方法遍历输入数组 arr。reduce 方法的第一个参数是一个累加器函数,它接收两个参数:

    • accu: 累加器,这里是一个 Map 对象,用于存储分组后的结果。键是根据 groupByKeys 生成的字符串,值是分组后的对象。
    • curr: 当前正在处理的数组元素。
  4. 生成分组键: 使用 groupByKeys.map((key) => curr[key]) 从当前对象 curr 中提取用于分组的键的值,并将它们连接成一个字符串作为分组键。

  5. 创建或更新分组对象:

    • accu.get(key) || …: 尝试从累加器 accu 中获取与当前分组键对应的对象。如果不存在,则创建一个新的对象。
    • Object.assign(…): 如果分组键不存在,则使用 Object.assign 创建一个新的对象,该对象包含:
      • 从 groupByKeys 中提取的键值对。
      • 从 sumKeys 中提取的键,其初始值为 0。
  6. 累加求和: 遍历 sumKeys 数组,将当前对象 curr 中对应键的值累加到分组对象中。

  7. 返回结果: 将累加器 accu 中的所有值提取到一个新的数组中,并返回该数组。

  8. 类型安全: 函数的返回类型 Pick[] 确保返回的数组中的对象只包含用于分组的键 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。

注意事项

  • groupBySum 函数会丢弃任何未参与转换的键。这意味着,如果原始对象包含其他属性(例如 size),则这些属性将不会出现在结果对象中。
  • 用于求和的键必须是数值类型。
  • 此实现依赖于 Object.fromEntries,它在较旧的 JavaScript 环境中可能不可用。如果需要支持这些环境,可以使用 polyfill。

总结

groupBySum 函数提供了一种通用且类型安全的方法,可以根据任意数量的对象键对对象数组进行分组,并对另一组任意数量的键的值进行求和。 通过利用 TypeScript 的类型系统,该函数可以在编译时捕获错误,并确保代码的健壮性和可维护性。

温馨提示: 本文最后更新于2025-08-17 22:38:53,某些文章具有时效性,若有错误或已失效,请在下方留言或联系易赚网
文章版权声明 1 本网站名称: 创客网
2 本站永久网址:https://new.ie310.com
1 本文采用非商业性使用-相同方式共享 4.0 国际许可协议[CC BY-NC-SA]进行授权
2 本站所有内容仅供参考,分享出来是为了可以给大家提供新的思路。
3 互联网转载资源会有一些其他联系方式,请大家不要盲目相信,被骗本站概不负责!
4 本网站只做项目揭秘,无法一对一教学指导,每篇文章内都含项目全套的教程讲解,请仔细阅读。
5 本站分享的所有平台仅供展示,本站不对平台真实性负责,站长建议大家自己根据项目关键词自己选择平台。
6 因为文章发布时间和您阅读文章时间存在时间差,所以有些项目红利期可能已经过了,能不能赚钱需要自己判断。
7 本网站仅做资源分享,不做任何收益保障,创业公司上收费几百上千的项目我免费分享出来的,希望大家可以认真学习。
8 本站所有资料均来自互联网公开分享,并不代表本站立场,如不慎侵犯到您的版权利益,请联系79283999@qq.com删除。

本站资料仅供学习交流使用请勿商业运营,严禁从事违法,侵权等任何非法活动,否则后果自负!
THE END
喜欢就支持一下吧
点赞15赞赏 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容