Flexible Arguments - Exercise

Contact Us or call 1-877-932-8228
Flexible Arguments - Exercise

Flexible Arguments

Duration: 10 to 15 minutes.

In this exercise, you will create a function that finds the maximum or minimum value among an indeterminate number of integer arguments.

  1. Open AdvancedFunctions/Exercises/flexibleArguments.html for editing.
  2. Write the body of function stats which accepts a parameter maxOrMin (a string, with value "max" or "min" to indicate whether to find the maximum or minimum) and accepts an arbitrary number of integer parameters.
  3. Use flexible arguments to allow the function to be called with any number of integers; for instance:
    • stats('max', 3, 49, 20, -3, 17) should return 49
    • stats('min', 22, 11, 38, -3, 17) should return -3
  4. Test your solution in a browser.

Solution:

AdvancedFunctions/Solutions/flexibleArguments.html
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>Flexible Arguments</title>
</head>
<body>
	<h1>Flexible Arguments</h1>
	<script>
		function stats(maxOrMin) {
			var myargs = Array.from(arguments).slice(1);
			if (myargs.length == 0) {
				return null;
			}
			if (maxOrMin == 'max') {
				var max = myargs[0];
			} else {
				var min = myargs[0];
			}
			for (var i in myargs) {
				if (maxOrMin == 'max') {
					if (myargs[i] > max) {
						max = myargs[i];
					}
				} else {
					if (myargs[i] < min) {
						min = myargs[i];
					}
				}
			}
			return maxOrMin == 'max' ? max : min;
		}

		document.write(stats('max', 3, 49, 20, -3, 17));
		document.write('<hr>');
		document.write(stats('min', 22, 11, 38, -3, 17));
	</script>
</body>
</html>

Code Explanation

We set local variable myargs to the array of arguments not including the first argument (Array.from(arguments).slice(1)) since the first parameter is the string representing whether we are to find the maxiumum or minimum value.

We set either a temporary max (if maxOrMin is "max") or temporary min, giving the variable the value of the first element in our array of arguments.

We then iterate over the arguments array, setting the current item to be the temporary max or min, as appropriate, and returning the final value.

Next