当然, 我很乐意为您提供一些复杂的 TypeScript reduce 方法的演示案例。Reduce 是一个非常强大的数组方法, 可以用于各种复杂的数据转换和计算。以下是几个高级示例:
- 分组计数:
interface Person {
name: string;
age: number;
department: string;
}
const employees: Person[] = [
{ name: "Alice", age: 30, department: "IT" },
{ name: "Bob", age: 35, department: "HR" },
{ name: "Charlie", age: 28, department: "IT" },
{ name: "David", age: 40, department: "Finance" },
{ name: "Eve", age: 32, department: "HR" },
];
const departmentCounts = employees.reduce((acc, employee) => {
acc[employee.department] = (acc[employee.department] || 0) + 1;
return acc;
}, {} as Record<string, number>);
console.log(departmentCounts);
// Output: { IT: 2, HR: 2, Finance: 1 }- 嵌套数组扁平化:
const nestedArray = [1, [2, 3], [4, [5, 6]], 7, [8, [9, [10]]]];
const flattenArray = (arr: any[]): number[] => {
return arr.reduce((acc, val) => {
return acc.concat(Array.isArray(val) ? flattenArray(val) : val);
}, []);
};
console.log(flattenArray(nestedArray));
// Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]- 构建树形结构:
interface TreeNode {
id: number;
name: string;
parentId: number | null;
children?: TreeNode[];
}
const flatData: TreeNode[] = [
{ id: 1, name: "Root", parentId: null },
{ id: 2, name: "Child 1", parentId: 1 },
{ id: 3, name: "Child 2", parentId: 1 },
{ id: 4, name: "Grandchild 1", parentId: 2 },
{ id: 5, name: "Grandchild 2", parentId: 2 },
];
const buildTree = (data: TreeNode[]): TreeNode[] => {
const idMapping = data.reduce((acc, el, i) => {
acc[el.id] = i;
return acc;
}, {} as Record<number, number>);
let root: TreeNode[] = [];
data.forEach((el) => {
if (el.parentId === null) {
root.push(el);
} else {
const parentEl = data[idMapping[el.parentId]];
parentEl.children = [...(parentEl.children || []), el];
}
});
return root;
};
console.log(JSON.stringify(buildTree(flatData), null, 2));- 函数组合:
type Func<T> = (arg: T) => T;
function compose<T>(...funcs: Func<T>[]): Func<T> {
return funcs.reduce((a, b) => (arg: T) => a(b(arg)));
}
const addOne = (x: number) => x + 1;
const double = (x: number) => x * 2;
const square = (x: number) => x * x;
const composedFunc = compose(addOne, double, square);
console.log(composedFunc(3)); // Output: 49
// (3^2 * 2) + 1 = 19- 实现 Promise. All:
function promiseAll<T>(promises: Promise<T>[]): Promise<T[]> {
return promises.reduce((acc, promise) => {
return acc.then((results) => {
return promise.then((result) => [...results, result]);
});
}, Promise.resolve([] as T[]));
}
const promise1 = Promise.resolve(3);
const promise2 = new Promise<string>((resolve) => setTimeout(() => resolve("foo"), 100));
const promise3 = Promise.resolve(42);
promiseAll([promise1, promise2, promise3]).then((values) => {
console.log(values); // Output: [3, "foo", 42]
});这些例子展示了 reduce 方法在处理复杂数据结构、函数式编程和异步操作等方面的强大能力。希望这些示例能够帮助您更好地理解和应用 TypeScript 中的 reduce 方法。
下面是 Gemini 1.5 Pro (0801) 生成的案例
下面是一个复杂的示例,展示如何使用 TypeScript 中的 reduce 方法来处理数组,并结合一些其他高阶函数,如 filter 和 map。这个示例涉及多步骤的数据处理,包括过滤、映射和聚合。
示例:处理复杂数据结构
假设我们有一个数组,包含一些用户信息,每个用户有多个订单。我们需要通过以下步骤来处理这些数据:
- 过滤:只保留那些订单总金额大于 100 的用户。
- 映射:将用户信息和他们的订单总金额进行关联。
- 聚合:计算所有用户的订单总金额。
代码示例
// 定义用户信息和订单数据类型
interface Order {
id: number;
amount: number;
}
interface User {
id: number;
name: string;
orders: Order[];
}
// 示例数据
const users: User[] = [
{
id: 1,
name: 'Alice',
orders: [
{ id: 1, amount: 50 },
{ id: 2, amount: 30 },
{ id: 3, amount: 20 },
],
},
{
id: 2,
name: 'Bob',
orders: [
{ id: 4, amount: 100 },
{ id: 5, amount: 200 },
],
},
{
id: 3,
name: 'Charlie',
orders: [
{ id: 6, amount: 20 },
{ id: 7, amount: 30 },
],
},
];
// 步骤 1:过滤出订单总金额大于 100 的用户
const filteredUsers = users.reduce((acc, user) => {
const totalAmount = user.orders.reduce((acc, order) => acc + order.amount, 0);
if (totalAmount > 100) {
acc.push({ ...user, totalAmount });
}
return acc;
}, [] as (User & { totalAmount: number })[]);
// 步骤 2:映射用户信息和他们的订单总金额
const mappedUsers = filteredUsers.map(user => ({
id: user.id,
name: user.name,
totalAmount: user.totalAmount,
}));
// 步骤 3:聚合所有用户的订单总金额
const totalOrderAmount = mappedUsers.reduce((acc, user) => acc + user.totalAmount, 0);
console.log('过滤后用户信息:', filteredUsers);
console.log('映射后用户信息:', mappedUsers);
console.log('所有用户的订单总金额:', totalOrderAmount);解释
-
过滤:
- 使用
reduce方法遍历users数组,计算每个用户的订单总金额,并将满足条件(总金额大于 100)的用户信息存入filteredUsers数组中。
- 使用
-
映射:
- 使用
map方法将filteredUsers数组中的每个用户信息进行映射,仅保留id、name和totalAmount属性。
- 使用
-
聚合:
- 使用
reduce方法将所有用户的totalAmount属性进行累加,得到最终的总金额。
- 使用
这个示例展示了如何通过组合使用 filter、map 和 reduce 方法来处理复杂的数据结构,并进行多步骤的数据转换.