Skip to content

Instantly share code, notes, and snippets.

@abhinavnigam2207
Last active February 27, 2021 21:11
Show Gist options
  • Save abhinavnigam2207/a32f83b5d972b5851c48cff5ba55d218 to your computer and use it in GitHub Desktop.
Save abhinavnigam2207/a32f83b5d972b5851c48cff5ba55d218 to your computer and use it in GitHub Desktop.
/* ******************** If Else/Switch Way ********************* */
const shape = 'circle';
const getArea1 = () => {
if (shape === 'circle') {
getCircleArea();
} else if (shape === 'triangle') {
getTriangleArea();
} else if (shape === 'rectangle') {
getRectangleArea();
} else if (shape === 'square') {
getSquareArea();
} else if (shape === 'pentagon') {
getPentagonArea();
} else if (shape === 'hexagon') {
getHexagonArea();
} else {
unIdentifiedShape();
}
}
// Another way to write the above piece, which is a bit better but still not great.
const getArea2 = () => {
switch (shape) {
case 'circle':
getCircleArea();
break;
case 'triangle':
getTriangleArea();
break;
case 'rectangle':
getRectangleArea();
break;
case 'square':
getSquareArea();
break;
case 'pentagon':
getPentagonArea();
break;
case 'hexagon':
getHexagonArea();
break;
default:
unIdentifiedShape()
}
}
/* ******************** Hashmap Way ******************** */
const shape = 'Circle';
const SHAPE_AREAS = {
circle: getCircleArea(),
triangle: getTriangleArea(),
rectangle: getRectangleArea(),
square: getSquareArea(),
pentagon: getPentagonArea(),
hexagon: getHexagonArea()
};
const getArea2 = () => {
SHAPE_AREAS[shape] || unIdentifiedShape();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment