Created
March 18, 2020 14:52
-
-
Save huynhsamha/0272e37439bfed78ada40a7151ecfb16 to your computer and use it in GitHub Desktop.
Recursive sort in typescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Playground: https://www.typescriptlang.org/play/?ssl=1&ssc=1&pln=39&pc=1#code/MYGwhgzhAEB2D2ATAptA3gWAFDV9C8ATgC4DyhKhAXHAK4C2ARsoQNzZ7QDCAFgJYhEhZLBoIUAbQC67LBzzB4sCMUK1gxIgAoCJcpTENmhAJTp5nXMX4QAdLrIUW0ALz4ijyrMt5rfO7wCQiKu0NIW0AC+2NFyWIrKxNCK9AAOYIRgmoShWmBiSMgANNCMBShmLgB85jh4fABm0Hm2gYLCsNAAZF3QYK387SK2ICIA5tbQNQCMZph1Pv1twbD2Hlop6ZnZJhGxnI3NjANBHd29x8sdI+OTM3MRnJeDK2skG-BpGVlEuwtREWExFohE6-Qc+mcAFpSm9PCxZLFsNgEipki8IOVkNJQtJZA0iM1Rkk+KEAKysaCkmoABkpfChUIe-2AGNsqVoEB4WlgyAA7nBClo+CYTIjkfElGjxMhMYLJFJcTJsASclpiVTQtM6ZrafTGczOKikp03LyBTLhWKIodhdAAKTQABMrjcNMNPjgJyGpvRQQg3jw+zwMrsHK5POtWCRWFDcI+X22vwlqPgoxG8DGPMKED+QA | |
class node { | |
sortOrder: number; | |
Children: node[]; | |
constructor(sortOrder: number) { | |
this.sortOrder = sortOrder; | |
this.Children = [] | |
} | |
} | |
const comparator = (a: node, b: node) => { | |
if (a.Children && a.Children.length > 1) { | |
a.Children.sort(comparator) | |
} | |
if (b.Children && b.Children.length > 1) { | |
b.Children.sort(comparator) | |
} | |
return a.sortOrder - b.sortOrder; | |
} | |
const childs: node[] = []; | |
for (let i = 5; i > 0; i--) { | |
childs.push(new node(i)); | |
} | |
const nodes: node[] = []; | |
for (let i = 10; i > 0; i--) { | |
const n = new node(i); | |
if (i % 2 == 0) { | |
n.Children = childs; | |
} | |
nodes.push(n); | |
} | |
nodes.sort(comparator) | |
console.log(nodes) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment