Last active
February 5, 2021 21:10
-
-
Save ngoryachev/9246aa33cd8ea1cae791aa3e1e575fa6 to your computer and use it in GitHub Desktop.
Print Tree Dart: Loop vs No-Loop Implementation (`¯\_(ツ)_/¯`)
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
class Node { | |
final String text; | |
final List<Node> nodes; | |
Node({this.text, this.nodes = const []}); | |
static void _printNodeLoop(Node node, [String space = '']) { | |
print('$space${node.text}'); | |
node.nodes.forEach((n) => _printNodeLoop(n, '${space}__')); | |
} | |
static void _printNodesNoLoop(List<Node> nodes, [String space = '']) { | |
var tail = <Node>[]; | |
if (nodes.isNotEmpty) { | |
tail = [...nodes]; | |
final head = tail.removeAt(0); | |
print('$space${head.text}'); | |
_printNodesNoLoop(head.nodes, space + '__'); | |
} | |
if (tail.isNotEmpty) { | |
_printNodesNoLoop(tail, space); | |
} | |
} | |
void printNodeLoop() { | |
_printNodeLoop(this); | |
} | |
void printNodeNoLoops() { | |
_printNodesNoLoop([this]); | |
} | |
} | |
void main() { | |
final testNode = | |
Node(text: 'a', nodes: [Node(text: 'b', nodes: [Node(text: 'b', nodes: [])]), Node(text: 'a')]); | |
testNode.printNodeLoop(); | |
print('== == VS == =='); | |
testNode.printNodeNoLoops(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment