I m looking for the best way to replace eval( "new object();" )
The ugly source :
//var type = window.$(droppedDomNode).data("shape");
var type = "sankey.shape.Start";
var figure = eval("new "+type+"();");
// create a command for the undo/redo support
var command = new draw2d.command.CommandAdd(this, figure, x, y);
The eval create a new sankey.shape.Start object.
I'm looking for best solution to replace this kind of code.
Thanks
I'd build an object (mapping) of constructor functions.
const constructors = {
"sankey.shape.Start": () => new sankey.shape.Start(),
// etc... (this could be built programmatically)
};
Then,
const figure = constructors[type]();
You can split it and walk up the path from window if it is global
var foo = {
bar: {
world: 'baz',
}
}
const getIt = (str, start = window) => {
return str.split(/\./).reduce((o, k) => o[k], start);
}
const x = "foo.bar.world";
console.log(getIt(x))