поэтому причина, по которой цвет границы и цвет фона не совпадают, заключается в том, что вы вызываете функцию для каждого свойства, для которого вам нужен цвет. одни только функции не имеют какого-либо состояния, поэтому сама функция не может вспомнить, что функция возвращала ранее.
Лучший способ, который я мог бы себе представить, это также сохраняет хороший декларативный способ. вы выложили свои данные с помощью класса.
class GenerateColorPairs {
constructor(numOfColorPairs) {
this.tickCycle = 2
this.currentTick = 0
this.colorSetIndex = 0
this.colorSet = []
const letters = '0123456789ABCDEF';
for (let i = 0; i < numOfColorPairs; i++) {
let color = '#';
for (let j = 0; j < 6; j++) {
color += letters[Math.floor(Math.random() * 16)];
}
debugger;
this.colorSet.push(color)
}
}
tick() {
if (this.currentTick < this.tickCycle) {
this.currentTick += 1
} else if (this.currentTick === this.tickCycle) {
if (this.colorSetIndex === this.numOfColorPairs) {
throw new Error(`
function has been called more times than
the 'numOfColorPairs' x2\n To be able to use this
function more than ${this.numOfColorPairs} times,
pass a higher value when instanciating to the class
constructor
`)
}
this.colorSetIndex += 1
this.currentTick = 0
}
}
generateColor() {
this.tick()
return this.colorSet[this.colorSetIndex];
}
}
var colors = new GenerateColorPairs(2)
var data = [{
label: "records",
data: [2, 4, 20, 10],
fill: false,
backgroundColor: colors.generateColor(),
borderColor: colors.generateColor(),
borderWidth: 1
}, {
label: "amount",
data: [100, 200, 500, 50],
fill: false,
backgroundColor: colors.generateColor(),
borderColor: colors.generateColor(),
borderWidth: 1
}];
console.log(data)
Это гораздо более многословно, чем другие опции, упомянутые здесь, но позволяет вам объявлять все ваши данные в одном операторе и не проходить их через фабрику.