I am currently working on refactoring two methods that exist in directives into a service.
This is method one:
scope.computeStyle = (component) ->
elementHash = {}
if component.element.type == 'table'
elementHash.height = 600
if component.height?
elementHash.height = component.height * 50
else if component.element.type == 'single_value'
elementHash.height = 200
elementHash.width = 800
return elementHash
This is method two:
scope.computeStyle = (element, rowComponent) ->
elementHash = {}
if element.type == 'table'
elementHash.height = 600
if rowComponent?.height?
elementHash.height = rowComponent.height
else if element.type == 'single_value'
elementHash.height = 200
elementHash.width = 800
return elementHash
They both do the same thing (a little differently). They take an element/component
(which are objects containing data about an object in my application), checks what type of object they are (in this case, a table or a single value), and applies a height and/or width transformation.
Within my service, this is what I have done:
angular = require "angular"
angular.module("myapp.dashboards.layouts").service("DashboardLayoutComputeStyle" ->
@computeStyle = (componentElement, height) ->
elementHash = {}
if componentElement.type == 'table'
elementHash.height = 600
if height?
elementHash.height = height
else if element.type == 'single_value'
elementHash.height = 200
elementHash.width = 800
return elementHash
@
)
Here's where my question comes in:
I am not sure what to do at this line in my abstracted method:
if height?
elementHash.height = height
In method one, this is what it looks like:
if component.height?
elementHash.height = component.height * 50
In method two, this is what it looks like:
if rowComponent?.height?
elementHash.height = rowComponent.height
I have three constraints to the refactoring of these two lines:
I must check whether both
rowComponent
andheight
exist in method twoI don't need to check whether
component
exists, but I must check whetherheight
exists in method oneIn method one, I must set the
elementHash,height
tocomponent.height * 50
, while in method two, I can simply assignrowComponent.height
toelementHash.height
How would I abstract these two lines out?