I have the following code in JavaScript:
const calculateDiameter = (circle) => ({
get diameter() {
return (circle.radius * 2);
}
});
const calculateCircumference = (circle) => ({
get circumference () {
return (2 * (22 / 7) * circle.radius)
}
});
const createCircle = (radius) => {
const circle = {
radius
};
return Object.assign(
circle,
calculateDiameter(circle),
calculateCircumference(circle)
)
}
// Create a cirlce
const myCircle = createCircle(2);
console.log( myCircle.diameter ) // returns: 4
console.log( myCircle.circumference ) // returns: 12.571428571428571
What I'd like to do is pass the output of calculateDiameter() to calculateCircumference(), so here is what I did:
// The following function was NOT modified
const calculateDiameter = (circle) => ({
get diameter() {
return (circle.radius * 2);
}
});
const calculateCircumference2 = (circle) => ({
get circumference () {
return ((22 / 7) * circle.diameter)
}
});
const createCircle2 = (radius) => {
const circle = {
radius
};
const circleWithDiameter = Object.assign(
circle,
calculateDiameter(circle),
)
return Object.assign(
circleWithDiameter,
calculateCircumference2(circleWithDiameter)
)
}
// Create a cirlce
const myCircle2 = createCircle2(2);
console.log( myCircle2.diameter ) // returns: 4
console.log( myCircle2.circumference ) // returns: 12.571428571428571
Is this approach described in createCircle2() correct? In other words, should I create a middle step object (i.e., circleWithDiameter) to allow me to pass the diameter to calculateCircumference2()? It seems like an overload. Is there a more succinct way or direct way to call calculateDiameter() from within calculateCircumference2()?
The reason for this question is I will have a very complex object (as opposed to the circle), and those middle steps seem to be too convoluted.