Chartjs-How to I optimise these javscript options which is used multiple times on different chart.js graphs?

1👍

You can define your options object separately:

const chartOptions = {
    tooltips: {enabled: false},
    maintainAspectRatio: false,
    // ...
};

then use it where you need it:

new Chart(progressStackAll, {
    type: 'horizontalBar',
    // ...
    options: chartOptions,
});

Looking at your options, it seems unlikely that the Chart constructor modifies the object you give it. But if it did, you could just do a shallow copy:

new Chart(progressStackAll, {
    type: 'horizontalBar',
    // ...
    options: {...chartOptions},
});

If it changed one of the subobjects on options (again: this seems unlikely), you could do a deep copy or write a function that returns a new options object each time:

function createChartOptions() {
    return {
        tooltips: {enabled: false},
        maintainAspectRatio: false,
        // ...
    };
}

Then:

new Chart(progressStackAll, {
    type: 'horizontalBar',
    // ...
    options: createChartOptions(),
});

Leave a comment