Last active
January 19, 2016 10:27
-
-
Save glaznaj/d4af2bb7bfbe65fd5629 to your computer and use it in GitHub Desktop.
Dart version of tree.ts
This file contains hidden or 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
// tree.ts https://gist.github.com/dmitry-vsl/ab40c3b325bcf0a0eb07 | |
// Run it in Dartpad: https://dartpad.dartlang.org/1a4a46dce98278473255 | |
class Tree<T> { | |
final Tree<T> left; | |
final Tree<T> right; | |
final T value; | |
Tree(this.left, this.right, this.value); | |
factory Tree.fromMap(Map map) { | |
if (map == null) return null; | |
assert(map.containsKey('left')); | |
assert(map.containsKey('right')); | |
assert(map.containsKey('value')); | |
return new Tree<T>( | |
new Tree.fromMap(map['left']), | |
new Tree.fromMap(map['right']), | |
map['value'] | |
); | |
} | |
Map toMap() => { | |
'left': left?.toMap(), | |
'right': right?.toMap(), | |
'value': value | |
}; | |
// We are losing type of "a" here. | |
// https://github.com/dart-lang/dart_enhancement_proposals/issues/22 | |
reduce(initial, reducer(a, T b)) { | |
var withNodeValue = reducer(initial, value); | |
var withLeftBranch = left?.reduce(withNodeValue, reducer); | |
var withRightBranch = right?.reduce(withLeftBranch ?? withNodeValue, reducer); | |
return withRightBranch ?? withNodeValue; | |
} | |
} | |
num average(Tree<num> tree) { | |
var reducer = (averageAcc, num val) => { | |
'sum': averageAcc['sum'] + val, | |
'count': averageAcc['count'] + 1 | |
}; | |
var result = tree.reduce({'sum': 0, 'count': 0}, reducer); | |
return result['sum'] / result['count']; | |
} | |
main() { | |
var treeMap = { | |
'value': 4, | |
'left': { | |
'value': 5, | |
'left': null, | |
'right': null | |
}, | |
'right': { | |
'value': 1, | |
'left': null, | |
'right': { | |
'value': 2, | |
'left': null, | |
'right': null | |
} | |
}, | |
}; | |
var tree = new Tree<num>.fromMap(treeMap); | |
print(average(tree)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment