patternMinor
Searching an object tree structure
Viewed 0 times
objectstructuresearchingtree
Problem
I have this recursive function that searches an object tree structure:
Which I then call thus:
It works just fine so I am happy about that, but I am pretty new to CoffeeScript and would like feedback on the way I structured it. The loop I used seems a bit old school, so could I have used a comprehension here instead? Any other feedback would be great as I am still getting my head into the CoffeeScript idiom.
Please let me know if I should edit with more context code.
dataSearcher = (dataElement, identifierToFind) ->
if dataElement.identifier == identifierToFind
return dataElement
else
for childDataElement in dataElement.children
found = dataSearcher childDataElement, identifierToFind
if found then return foundWhich I then call thus:
foundDataElement = dataSearcher @options.nodeData, identifierIt works just fine so I am happy about that, but I am pretty new to CoffeeScript and would like feedback on the way I structured it. The loop I used seems a bit old school, so could I have used a comprehension here instead? Any other feedback would be great as I am still getting my head into the CoffeeScript idiom.
Please let me know if I should edit with more context code.
Solution
I'd prefer writing it like this:
Changes:
dataSearcher = (element, identifier) ->
return element if element.identifier is identifier
for child in element.children
found = dataSearcher child, identifier
return found if foundChanges:
- guard style instead of
else(one less level of indentation)
- postfix
if(probably a question of style)
isinstead of==
- shorter variable names
Code Snippets
dataSearcher = (element, identifier) ->
return element if element.identifier is identifier
for child in element.children
found = dataSearcher child, identifier
return found if foundContext
StackExchange Code Review Q#7618, answer score: 6
Revisions (0)
No revisions yet.