I have a collection of shapes in an object, each assigned with a specific color:
const shapeDesign = {
designId: 1,
shapes: [
{ shapeId: 'basic-square', color: { r: 255, g: 255, b: 255 }},
{ shapeId: 'basic-circle', color: { r: 255, g: 255, b: 255 }},
{ shapeId: 'basic-diamond', color: { r: 255, g: 0, b: 0 }},
{ shapeId: 'basic-rectangle', color: { r: 0, g: 255, b: 0 }}
]
}
In order to calculate the average color values for each design, I aim to achieve the following output:
Design 1: {r: 191.25, g: 191.25, b: 127.5 }
Considering performance efficiency (Big O notation), what is a more optimal approach to solve this issue?
My initial solution was deemed inefficient, presented below:
const computeAverage = (values) => values.reduce((total, current) => total + current, 0) / values.length;
const { shapes } = shapeDesign;
const reds = shapes.map(shape => shape.color.r)
const greens = shapes.map(shape => shape.color.g)
const blues = shapes.map(shape => shape.color.b)
console.log(`Design ${shapeDesign.designId}: {r: ${computeAverage(reds)}, g: ${computeAverage(greens)}, b: ${computeAverage(blues)} }`)