I have defined two charts below for example. But I use more than 50 charts in my code. The difference between both charts are: chartNumber, containerNumber, id, text and data. Also the condition that is used for checking each chart at the beginning.
Working fiddle of the same: https://jsfiddle.net/2s93zb4j/12/ (pls check all 3 charts to view all of them)
Instead of repeating same lines of code for each chart, will I be able to reduce the number of lines using for loop or forEach. Thank you.
//Chart1
if (checkNA=== "NA")
chart0 = Highcharts.chart('container1', {
id: 1,
yAxis: [{
title: {
text: 'NorthAmerica'
}
}],
series: [{
data: NorthAmericaData,
type: 'line',
}],
});
}
//Chart2
if (checkSA=== "SA")
chart1 = Highcharts.chart('container2', {
id: 2,
yAxis: [{
title: {
text: 'SouthAmerica'
}
}],
series: [{
data: SouthAmericaDta,
type: 'line',
}],
});
}
CodePudding user response:
You can use a class, such as:
class Chart {
constructor(id, container, check, data, title) {
this.id = id;
this.container = container;
this.check = check;
this.data = data;
this.title = title;
}
create() {
if (this.check === "NA" || this.check === "SA") {
const highchart = Highcharts.chart(this.container, {
id: this.id,
yAxis: [{
title: {
text: this.title
}
}],
series: [{
data: this.data,
type: 'line',
}]
});
}
}
}
Then implement it like this:
const chart1 = new Chart(1, 'container1', checkNA, NorthAmericaData, 'NorthAmerica');
chart1.create();
const chart2 = new Chart(2, 'container2', checkSA, SouthAmericaData, 'SouthAmerica');
chart2.create();
CodePudding user response:
A class would go a long way here.
class ChartObject {
constructor(id, text, data) {
this.id = id;
this.yAxis = [
{
title: {
text,
},
},
];
this.series = [
{
data,
type: 'line',
},
];
}
}
//Chart1
if (checkNA === 'NA') {
chart0 = Highcharts.chart(
'container1',
new ChartObject(1, 'NorthAmerica', NorthAmericaData)
);
}
//Chart2
if (checkSA === 'SA') {
chart1 = Highcharts.chart(
'container2',
new ChartObject(2, 'SouthAmerica', SouthAmericaDta)
);
}
Hope this helps.