I have two very similar functions that exist mainly for syntactic sugar.

deactivate = (el, seek) -> el.find(seek).removeClass("active")
activate = (el, seek) -> el.find(seek).addClass("active")

This allows me to write, for example:

activate $("#something"), ".child"

Using the above purely as an example, ignoring any logical errors with the JavaScript itself… how could this be refactored to be more dry?


2 Answers 2


You can use js' bracket notation for this task

alter = (el, seek, method) -> el.find(seek)[method + "Class"]("active")
#use like this:
alter $("#something"), ".child", "add"

However, your situation doesn't really call for DRYness. Your method names make more sense than alter, or whichever name you may choose.

  • \$\begingroup\$ You could just use your alter function as a stepping stone for the definitions of activate/deactivate become more DRY: deactivate = (el, seek) -> alter el, seek, "remove" activate = (el, seek) -> alter el, seek, "add" (Disclamer: I don't use CoffeScript) \$\endgroup\$
    – RoToRa
    Dec 19, 2011 at 13:56
  • \$\begingroup\$ @RoToRa Correct, and you can also do it the other way around: Store activate and deactivate on an object, and pass which one you want as an argument to alter: containingObject[method]("active") \$\endgroup\$
    – Zirak
    Dec 19, 2011 at 14:05
  • \$\begingroup\$ Thank you. I think the syntactic benefit of my initial functions outweigh the benefit of making the code more DRY. I was just wondering if there was something I was missing here. \$\endgroup\$
    – Toast
    Dec 19, 2011 at 20:43

I think your code is fine. I would only suggest a more complex solution only if this pattern happens more often.

For example, if you want to refactor to allow for other class names you can do something like this:

adder   = clsName -> (el, seek) -> el.find(seek).removeClass(clsName)
remover = clsName -> (el, seek) -> el.find(seek).addClass(clsName)

activate   = adder 'active'
deactivate = remover 'active'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.