1. 程式人生 > 其它 >一個包含巢狀遞迴資料結構的物件的排序實現

一個包含巢狀遞迴資料結構的物件的排序實現

技術標籤:TypeScript

本文和SAP Spartacus這個開源專案的一個issue有關:

https://github.com/SAP/spartacus/issues/9353

待排序的資料結構:人(Person)

在這裡插入圖片描述

person有一個欄位children,型別為一個數組,型別也是person.

任務:

寫一個排序函式,輸入引數為person型別的變數,將其children屬性裡包含的person陣列的元素進行遞迴排序。

完整原始碼:

// Import stylesheets
import "./style.css";

// Write TypeScript code!
const
appDiv: HTMLElement = document.getElementById("app"); appDiv.innerHTML = `<h1>TypeScript Starter</h1>`; interface person { id: number; name: string; age: number; children?: Array<person>; } let person1: person = { id: 1, name: "二十歲", age: 20, children: [
] }; let person2: person = { id: 2, name: "三十歲", age: 30 }; let person3: person = { id: 3, name: "十八歲", age: 18, children: [] }; let person4: person = { id: 4, name: "四十歲", age: 40 }; let person11: person = { id: 21, name: "二十歲小夥子1", age: 21 }; let person12: person =
{ id: 22, name: "二十歲小夥子2", age: 27 }; let person13: person = { id: 23, name: "二十歲小夥子3", age: 20 }; let person31: person = { id: 31, name: "三十歲小夥子1", age: 35 }; let person32: person = { id: 32, name: "三十歲小夥子2", age: 34 }; let person33: person = { id: 33, name: "三十歲小夥子3", age: 37 }; person1.children.push(person11); person1.children.push(person12); person1.children.push(person13); person3.children.push(person31); person3.children.push(person32); person3.children.push(person33); let god: person = { id: 0, name: "上帝", age: 0, children: [] }; god.children.push(person1); god.children.push(person2); god.children.push(person3); god.children.push(person4); const forSPASort = (input: person) => { let result: person; if (input.children) { input.children.sort(sorter); input.children.forEach(child => { forSPASort(child); }); } return input; }; const sorter = (a, b) => { console.log("Jerry, a: " + a.name + " b: " + b.name); return a.age - b.age; }; const result = forSPASort(god); console.log("result: " + result);