You are right, excessive logic if..then or switch is the smell of code and can almost always be reorganized into something more elegant. In this case, a factory based on a name can be reorganized into a dictionary with a key like this name and value as a function for return
var dictionary = {}; dictionary[TYPES.TEXT] = Text; dictionary[TYPES.WORD] = Word; dictionary[TYPES.PARAGRAPH] = Paragraph; dictionary[TYPES.TABLE] = Table; createElement = function(name, data){ return new dictionary[name](data); }
Real-time example: http://jsfiddle.net/KkMnd/
EDIT: This line in the createElement method may / should first verify that something is configured for the passed TYPES.* . A good way is to check for an element in an element before trying to call this method.
return (typeof dictionary[name] == 'function') ? new dictionary[name](data) : some_default_value;
Jamiec
source share