pertrai1 pertrai1 - 3 months ago 16
Javascript Question

Turn Object Literal into Reusable Class?

Is it possible to take this code below and make it so that it is easily reusable without having to copy and paste each time I want to create a new options:

optionA: {
chart: {
type: 'stacked',
color: 'red',
showControls: false
}
}


Now if I wanted to have another chart, I have to do this right now:

optionB: {
chart: {
type: 'line',
color: 'yellow',
showControls: false
}
}


It would be nice if there would be a way to create a class or something of sorts so that I can add a new option without having to reuse all of the same code, kinda like hiding everything that does not need to be known for the implementation. I have looked around for ways to do this but my searches have had no success.

EDIT: I might not have been enough information after looking at the responses so far. Here is the full data:

timelineA: {
chart: {
type: 'stackedAreaChart',
color: defaultColor,
showControls: false,
showLegend: false,
useInteractiveGuideline: true,
margin: margin,

x: AnalysisTransforms.xValue,
y: function(d){
return d[1];
},

forceY: [0, 1],

noData: $scope.translations.noData,
xAxis: {
showMaxMin: false,
tickPadding: 16,
tickFormat: AnalysisTransforms.formatDate,
tickValues: AnalysisTransforms.xAxisTicks
},
yAxis: {
tickPadding: 16,
tickFormat: AnalysisTransforms.formatInteger
}
}
}

timelineB: {
chart: {
type: 'line',
color: defaultColor,
showControls: false,
showLegend: false,
useInteractiveGuideline: true,
margin: margin,

x: AnalysisTransforms.formatLine,
y: AnalysisTransforms.linex,

noData: $scope.translations.noData,
xAxis: {
showMaxMin: false,
tickPadding: 16,
tickFormat: AnalysisTransforms.formatParseDate,
tickValues: AnalysisTransforms.xticks
},
yAxis: {
tickPadding: 16,
tickFormat: AnalysisTransforms.formatInteger
}
}
}


This is from angular-nvd3 and there is not enough support from the repo for me to figure this out. I have started playing around with creating a class for this but don't think I am following best practices because I don't know how to convert object literal like this into a class that I can new up for any charts I want to create.

What I see is that there is some code that is used between the 2 and then some that is not. I hope I am not confusing beyond the ability for help in this issue.

Answer

Something as:

var defaults = {
  color: defaultColor,
  showControls: false,
  showLegend: false,
  useInteractiveGuideline: true,
};

function buildChart(type, opts) {
  return Object.assign({
    type: type,
  },
  defaults,
  opts);
}

// Then you can do variations as 
var lineChart = buildChart('line', { color: '#CCC' });
var barChart = buildChart('bar', { color: 'red' });

In Object.assign it's important for opts to go last, so it can override the defaults when required.