Write area(shape, a, b) for "square", "rectangle", "circle" and "triangle", where b defaults to a (so a rectangle with one side is a square), and return a message for unknown shapes.
Solution
main.js
function area(shape, a, b = a) {
switch (shape) {
case "square": return a * a;
case "rectangle": return a * b;
case "circle": return +(Math.PI * a * a).toFixed(2);
case "triangle": return 0.5 * a * b; // base a, height b
default: return `Unknown shape: ${shape}`;
}
}
console.log(area("square", 5));
console.log(area("rectangle", 4, 6));
console.log(area("rectangle", 4));
console.log(area("circle", 3));
console.log(area("triangle", 10, 7));
console.log(area("hexagon", 2));
Output Verified by running it on Node.js
25
24
16
28.27
35
Unknown shape: hexagon
b = a uses the earlier parameter as a default. +(…).toFixed(2) rounds to two decimals and converts the string back to a number.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!