Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Must be done in Javascript. Professor X has written a JavaScript function findAverage() to help his students compute homework score averages. The findAverage() function returns

Must be done in Javascript.

Professor X has written a JavaScript function findAverage() to help his students compute homework score averages. The findAverage() function returns the average of an array of homework scores. Professor X's students complain that sometimes findAverage() returns NaN or unexpected answers. Professor X suspects the problems are due to students passing findAverage() an empty scores array or an array with improperly formatted scores. Modify findAverage() to throw exceptions for the following reasons:

1.) No scores are in the scores array.

2.) A negative score was found in the scores array.

3.) A non-integer was found in the scores array.

Wrap the existing function calls to findAverage() in a try-catch statement, and output any thrown exceptions to the console. The program should continue to try the next call to findAverage() regardless of any exceptions thrown.

To determine if a non-integer exists in the scores array, use the ECMAScript 6 method Number.isInteger(n), which returns true if n is an integer, and false otherwise. Some browsers do not yet support Number.isInteger(n), so a polyfill is provided for the method. A polyfill is code that provides functionality a web browser is currently lacking but may support in the future.

Here is the code:

// Returns the average of the numbers in the scores array. function findAverage(scores) { var sum = 0; scores.forEach(function(score) { sum += score; }); return sum / scores.length; }

console.log("Average = " + findAverage([90, 85, 71, 93])); console.log("Average = " + findAverage([76])); console.log("Average = " + findAverage([90, -85, 71, 93])); // Should not accept negative numbers console.log("Average = " + findAverage([])); // Should not accept empty arrays console.log("Average = " + findAverage([60, "cat", 70])); // Should not accept non-numbers

// For browsers that do not support the ES6 method Number.isInteger() Number.isInteger = Number.isInteger || function(value) { return typeof value === "number" && isFinite(value) && Math.floor(value) === value; };

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image_2

Step: 3

blur-text-image_3

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Object Oriented Databases Prentice Hall International Series In Computer Science

Authors: John G. Hughes

1st Edition

0136298745, 978-0136298748

More Books

Students also viewed these Databases questions