Monday, September 12, 2016

Flatten a Map of Maps

A question came up that interested me, someone had a map that contains children of possibly lists of other maps, and they wanted to flatten all these maps to count all the values contained in this map of lists of maps. I just used a recursive closure to collect all the values of the maps and lists, flatten that into a list and then an inject (fold) to count up the values.

def collector
collector = {item -> item.collect {element -> element.value instanceof Map ? collector(element.value) : element.value}}

assert 4 == collector([a: [q:1, w:1], b: [e:1], c: 1]).flatten().inject(0) { temp, val -> temp + val.value}
assert 3 == collector([a: [q:1, w:[z:1, x:1]]]).flatten().inject(0) { temp, val -> temp + val.value}

No comments:

Post a Comment