Exercise: Batch Calculator

Test your knowledge of functions by writing a function using a dispatch table.

Problem statement

In this challenge, make a function calculate using a dispatch table that takes an array of arrays of three elements as input, in the format [operand1, op, operand2]. Here, both operands are numbers and op can be any of plus, minus, times, dividedby, and raisedto. It should print an array containing the calculated answers via the application operand1 op operand2 for each subarray.

If a function that has not been defined in the dispatch table is used as an op in a subarray, or if it contains fewer or more elements than expected, just ignore this subarray.

Sample function call

calculate([5, 'minus', 2], [6, 'modulus', 2], [2, 'raisedto', 3], [3,'power',2], [91,'times',1])

Sample output

After skipping modulus and power, the output will be as follows:

3 8 91

Coding challenge

This is a simple problem related to the concept of anonymous functions that we previously covered. You must use this concept in your code and print the required results.

If you feel stuck, you can refer to the hints. For the solution, click the “Show Solution” button on the code playground. For further explanation of the solution, you can navigate to the next lesson.

Good luck!

Get hands-on with 1200+ tech skills courses.